简体   繁体   中英

JavaScript validation of string using regular expression

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._]*)/;

Try this regex:

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

See demo on regex101.com .

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!") } 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM