简体   繁体   English

jQuery验证方法(RegEx)

[英]jQuery Validation Method (RegEx)

$.validator.addMethod('username', function (value) {
    return [A-Za-z0-9\-\_]+.test(value);
}, 'Username can only contain letters, numbers, underscores and dashes.');

I am no good with regular expressions OR jQuery/JavaScript which makes this almost impossible for me. 我不熟悉正则表达式或jQuery / JavaScript,这对我来说几乎是不可能的。

I simply want to add a method to validate a username to make sure it only has numbers, letters, underscores, and dashes (no spaces, periods, etc) but I can't seem to get it right. 我只是想添加一个方法来验证用户名,以确保它只有数字,字母,下划线和短划线(没有空格,句号等),但我似乎无法正确使用它。

Any help would be appreciated. 任何帮助,将不胜感激。

There are two problems here. 这里有两个问题。 One, the regex needs delimiters. 一,正则表达式需要分隔符。 Two, the regex does not check whether the whole string is made up of those letters: 二,正则表达式不检查整个字符串是否由这些字母组成:

var regex = /^[\w-]+$/;
return regex.test(value);

I also shortened the regex a bit (the character class is the same). 我也缩短了正则表达式(字符类是相同的)。

您想将代码更改为:

return (value.match(/^[A-Za-z0-9-_]+$/));

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

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