开发者

javascript regex validation

开发者 https://www.devze.com 2022-12-29 02:40 出处:网络
Is there any way to find which input character fails the regex pattern. For ex: consider [A-Za-z\\s.&] is only allowable but the user enter like \"test/string\" where \'/\' invalidates input. How

Is there any way to find which input character fails the regex pattern.

For ex: consider [A-Za-z\s.&] is only allowable but the user enter like "test/string" where '/' invalidates input. How to f开发者_运维技巧ind who fails regex (our case '/')


You could remove the valid chars and you'll have a string of the invalid ones:

var invalid = "test/string".replace(/[A-Za-z\s.&]/g,""); // results in "/"


Just negate your character class and find out which character(s) match.

[^A-Za-z\s.&]

will match the / in test/string. So, altogether you get

if (/^[A-Za-z\s.&]+$/.test(subject)) {
    // Successful match
} else {
    result = subject.match(/[^A-Za-z\s.&]/g);
    // result is an array that contains all the characters that failed the match
}


To find which characters fails, split it with /[A-Za-z\s.&]+/, you will get invalid characters list

"test/string".split(/[A-Za-z\s.&]+/).join('')
/

To check username is valid or not, you could just use ^ and $ anchors.

/^[A-Za-z\s.&]+$/
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号