简体   繁体   English

使用正则表达式对字符串进行JavaScript验证

[英]JavaScript validation of string using regular expression

I have to validate string field which start with A-za-z and can contain 0-9_ . 我必须验证以A-za-z 0-9_并且可以包含0-9_字符串字段。 I have to set limit min 1 char and max 10 char. 我必须设置限制,最小1个字符,最大10个字符。

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

Try this regex: 试试这个正则表达式:

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

See demo on regex101.com . 请参阅regex101.com上的演示

I have to validate string field which start with A-za-z and can contain 0-9_ . 我必须验证以A-za-z 0-9_并且可以包含0-9_字符串字段。

I guess A-za-z is a typo, you meant A-Za-z . 我猜A-za-z是一个错字,您的意思是A-Za-z That is easy, we use ^ for the string start and [A-Za-z] character class for the letter. 这很容易,我们使用^表示字符串开头,使用[A-Za-z]字符类表示字母。

I have to set limit min 1 char and max 10 char. 我必须设置限制,最小1个字符,最大10个字符。

That means, we already have the "min 1 char" requirement fulfilled at Step 1 (one letter at the start). 这意味着,我们已经在步骤1中满足了“最少1个字符”的要求(开头为一个字母)。 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, $ ). 现在,我们可能会有字母,数字或下划线,出现0到9次-也就是说,我们需要使用{0,9}限制量词-直到字符串的末尾(即$ )。 A shorthand pattern in JS regex for letters, digits, and underscore is \\w . JS正则表达式中用于字母,数字和下划线的简写模式是\\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. 不要尝试使用正则表达式检查字符串的长度,在大多数情况下,它很慢且很麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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