Home > database >  regular expression in javascript
regular expression in javascript

Time:12-10

I'm trying to create regex for the following validation:

  1. 5 to 15 characters
  2. only letters and numbers allowed
  3. no numbers at the beginning or the end

/^[A-Za-z][A-Za-z0-9]([A-Za-z0-9] )$/ this for the 2nd & 3rd validation

so how can I add 5 to 15 characters validation to this regexp I tried to write it like that but it doesn't work /^[A-Za-z][A-Za-z0-9]([A-Za-z0-9] ){5,15}$/

CodePudding user response:

This should be what you want. Check for a letter at start and beginning, and the center can be 3 to 13 letters or digits

^[A-Za-z][\dA-Za-z]{3,13}[A-Za-z]$

CodePudding user response:

Here is a solution that uses a positive lookahead:

[
  'A23Z',
  'A234Z',
  'A2345678901234Z',
  'A23456789012345Z',
  '123456789Z',
  'A223456789',
].forEach(str => {
  let ok = /^(?=[a-zA-Z0-9]{5,15}$)[a-z-A-Z].*[a-z-A-Z]$/.test(str);
  console.log(str   ' => '   ok);
});

Output:

A23Z => false
A234Z => true
A2345678901234Z => true
A23456789012345Z => false
123456789Z => false
A223456789 => false

Explanation of regex:

  • ^ -- anchor at start of string
  • (?=[a-zA-Z0-9]{5,15}$) -- positive lookahead for 5 to 15 alphanum chars
  • [a-z-A-Z] -- expect alpha char
  • .* -- greedy scan
  • [a-z-A-Z] -- expect alpha char
  • $ -- anchor at end of string

Note: @nigh_anxiety's answer is shorter. I added this answer for educational purposes

CodePudding user response:

I think you can achieve this with JS code also. Just pass the string which you want to validate in the function and you will come to know whether it is valid or not.

const isValid = (stringToValidate) => {
if(stringToValidate && stringToValidate.length >=5 && 
stringToValidate.length <= 15   && stringToValidate.match("^[A-Za-z0- 
9] $") && 
!/^\d $/.test(stringToValidate.charAt(0))  && 
!/^\d $/.test(stringToValidate.charAt(stringToValidate.length-1))
)
return true;
return false;
}

const str = "Sachin22ss";
const valid =  isValid("Sachin22ss")
console.log("Validation of ",str, valid);
  • Related