0

I have to validate string field which start with A-za-z and can contain 0-9_. I have to set limit min 1 char and max 10 char.

Exp=/^([a-zA-Z]) +([0-9._]*)/;
3

3 Answers 3

1

Try this regex:

/^[a-zA-Z][0-9_]{0,9}$/

See demo on regex101.com.

Sign up to request clarification or add additional context in comments.

Comments

0

I have to validate string field which start with A-za-z and can contain 0-9_.

I guess A-za-z is a typo, you meant A-Za-z. That is easy, we use ^ for the string start and [A-Za-z] character class for the letter.

I have to set limit min 1 char and max 10 char.

That means, we already have the "min 1 char" requirement fulfilled at Step 1 (one letter at the start). Now, we may have letters, digits, or an underscore, 0 to 9 occurrences - that is, we need to use {0,9} limiting quantifier - up to the end of string (that is, $). A shorthand pattern in JS regex for letters, digits, and underscore is \w.

Use

/^[a-zA-Z]\w{0,9}$/

var re = /^[a-zA-Z]\w{0,9}$/; 
var str = 'a123456789';
if (re.test(str)) {
  console.log("VALID!")
} else { 
  console.log("INVALID!")
}
 

Comments

0
function isValid(string){
    if (string.length < 1 || string.length > 10)
        return false;
    return /^[a-zA-Z][0-9_]*$/.test(string);
}

console.assert(isValid("A"));
console.assert(isValid("a12345"));
console.assert(!isValid(""));
console.assert(!isValid("x123456787212134567"));
console.assert(!isValid("abcdef"));
console.assert(!isValid("012345"));

Don't try to check string length with regex, in most of the cases it is slow and burdensome.

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.