0

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}$/

3 Answers 3

1

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]$
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Thanks for expanding. I kept my answer brief as I was typing on mobile.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.