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._]*)/;
I have to validate string field which start with
A-za-zand can contain0-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!")
}
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.
a1?