﻿ How to Apply the Length Condition on the Existing Regular Expression - ITCodar

# How to Apply the Length Condition on the Existing Regular Expression

## How to apply the length condition on the existing regular expression

You could use a positive lookahead `(?=.{2,30}\$)` to check for the number of characters and you have to use a quantifier `+` for the character class in the middle character class and add matching the ranges as well.

If there can be multiple spaces:

``^(?=.{2,30}\$)[0-9a-zA-Z][0-9a-zA-Z ]*[0-9a-zA-Z]\$``

That will match

• `^` Start
• `(?=.{2,30}\$)` Positive lookahead to assert 2-30 characters
• `[0-9a-zA-Z]` Match one of the char class
• `[0-9a-zA-Z ]*` Match 0+ times any of the char class including a space
• `[0-9a-zA-Z]` Match one of the char class
• `\$` End

Edit

Without a lookahead this can also be written as

`^[A-Za-z0-9][A-Za-z0-9 ]{0,28}[A-Za-z0-9]\$`

## RegEx: How to match a whole string with fixed-length region with negative look ahead conditions that are overriden afterwards?

You could assert that the first 5 characters are either digits or `-` and make sure that there is no - before a digit in the first 5 chars.

``^(?![\d-]{0,3}-\d)(?=[\d-]{5})[A-Z\d-]+\$``
• `^` Start of string
• `(?![\d-]{0,3}-\d)` Make sure that in the first 5 chars there is no `-` before a digit
• `(?=[\d-]{5})` Assert at least 5 digits or `-`
• `[A-Z\d-]+` Match 1+ times any of the listed characters
• `\$` End of string

Regex demo

If atomic groups are available:

``^(?=[\d-]{5})(?>\d+-*|-{5})[A-Z\d_]*\$``
• `^` Start of string
• `(?=[\d-]{5})` Assert at least 5 chars `-` or digit
• `(?>` Atomic group
• `\d+-*` Match 1+ digits and optional `-`
• `|` or
• `-{5}` match 5 times `-`
• `)` Close atomic group
• `[A-Z\d_]*` Match optional chars A-Z digit or `_`
• `\$` End of string

Regex demo

## Length of entire regex pattern

I would use an alternation here to cover both integers (no decimal point) and floats (has a decimal point):

``^(?:\d{1,10}|(?![\d.]{11,})\d+\.\d+)\$``

Demo

Here is a breakdown of the above regex:

``^                   from the start of the input    (?:\d{1,10}     match 1 to 10 digits, no decimal point    |               OR    (?![\d.]{11,})  assert that we DON'T see more than 10 digits/decimal point    \d+\.\d+)       then match a floating point number (implicitly 10 chars max)\$                   end of the input``

## Regular Expressions, Length check in Javascript

Option 1: You can use `text-transform: capitalize` CSS property which will automatically do the task of converting a name from `john cena` to `John Cena`.

Check the example below in the CSS

Option 2:
I have added a new input called `Nick name` which uses javascript to do the same task.

I have used `keyup` handler to capture the all key input event so that we can execute a piece of code which will do the job on capitalizing the name.

The result is simple string manipulation which splits the name with `<space-character>` and converts the first character to uppercase and joins the same with rest of the string.

``document.addEventListener("DOMContentLoaded", function() {  document.querySelector("#NickName").addEventListener("keyup", capitalizeName);});function capitalizeName() {  if (!this.value) return;  var aNewName = this.value.split(" ").map(function(name) {    return name.charAt(0).toUpperCase() + name.substring(1);  });  this.value = aNewName.join(" ");}function validateForm() {  for (var i = 0; i < document.forms[0].elements.length; i++) {    var pedio = document.forms[0].elements[i];    if (pedio.id.indexOf("Name") != -1) {      if (pedio.value.length < 5 || pedio.value.length > 35) {        alert("Full Name must be 5-35 character long");        pedio.focus();        pedio.style.backgroundColor = "#997379";        return false;      }    }    if ((pedio.id.indexOf("Phone") != -1) && (isNaN(pedio.value))) {      alert("Phone is must contain only numbers");      pedio.focus();      pedio.style.backgroundColor = "#997379";      return false;    }    if (pedio.id.indexOf("Phone") != -1) {      if (pedio.value.length != 10) {        alert("Phone must be 10 numbers");        pedio.focus();        pedio.style.backgroundColor = "#997379";        return false;      }    }  }}``
``/* No CSS */#Name {  text-transform: capitalize;}``
``<h1 class="Title">Sign Up</h1><div>  <form method="post" onsubmit="return validateForm()">    <input type="text" id="Name" name="yourname" placeholder="*Full Name" autocomplete="off" required>    <input type="text" id="NickName" name="NickName" placeholder="*Nick name" autocomplete="off" required>    <input type="email" id="Email" name="youremail" placeholder="*E-Mail" autocomplete="off" required>    <input type="tel" id="Phone" name="yourphone" placeholder="*Phone" autocomplete="off" required>    <input type="password" id="Password" name="yourpassword" placeholder="*Password" autocomplete="off" required>    <p class="signup"> The fields with * are required!<br> -If you have an account, <a class="signup" href="reservation.php">log in</a> now-</p>    <keygen name="security" style="display:none;">    <input type="submit" value="Register">  </form></div>``

## Complex regex pattern with specific length

I think you can use

``^(?=[0-9-]{10}\$)\d+(?:-\d+)+\$``

See the regex demo

Details:

• `^` - start of string
• `(?=[0-9-]{10}\$)` - the string should only consist of 10 chars, either digits or `-`
• `\d+` - 1 or more digits
• `(?:-\d+)+` - 1 or more sequences of `-` followed with 1+ digits
• `\$` - end of string.

## Regular expression with a conditional statement that validates a phone number in JavaScript

• The round brackets are not for fun: if you don't want to capture anything then don't use them. Use them only for your `(this|that)` problem, where the pipe works as an OR operator.
• The square brackets don't need ranges if all you allow are 2 characters.
• If one character is mandatory then just write it. Don't put it in square brackets, and don't put it in round brackets.
• `?` is a quantifier, meaning what came before is optional (can occur 0 times or once). If you put that behind your zero then you make it the opposite of "must be in there".

With that knowledge in mind and writing the regex onto multiple lines and ignoring any whitespaces inbetween it then comes to:

``^0(   [67][0-9]{8}  |   8[1-4][0-9]{7}  )\$``

I also removed the optional whitespaces after your phone number: you nowhere explained that you wanted such a thing, nor was it in your list. It makes no sense either to allow spaces only after the phone number but not in front. So the ` *` part is not for fun either.

I also strongly discourage from using regex on phone numbers: people tend to input phone numbers not without spaces or hyphens inbetween. Have a look at all the existing Qs.