jQuery jquery字母数字验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11532982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery alphanumeric validation
提问by user1334095
$('#reg_submit').click(function () {
var reg_password1 = $('#reg_password1').val();
letters = /([a-z])([0-9])/;
var errorMessage = '';
if ( ! reg_password1.value.match(letters) )
{
errorMessage = "Password must be alphanumeric";
$('#msg_regpass1').html(errorMessage).show();
}
else {
$('#msg_regpass1').html('').hide();
}
});
i used the above jquery code for applying alphanumeric validation to my registration page.but i am getting the javascript error related to match(), something match is undefined like that. can anyone suggest the solution for the above problem or please provide some other code for getting alphanumeric validation for above code. that letters pattern also not working properly for alphanumeric validation.can anyone suggest other pattern
我使用上面的 jquery 代码将字母数字验证应用于我的注册页面。任何人都可以为上述问题提出解决方案,或者请提供一些其他代码以获取上述代码的字母数字验证。该字母模式也无法正常用于字母数字验证。任何人都可以建议其他模式
thanks in advance
提前致谢
回答by silentw
回答by Ray Toal
As all you asked for is a suggestion, here's a start: The regex you probably want is /^[a-z\d]+$/i
. Your existing regex matches only when your regex contains a single lowercase letter or digit anywhere in the string; the suggestion says that every character must be.
由于您要求的只是一个建议,因此这是一个开始:您可能想要的正则表达式是/^[a-z\d]+$/i
. 仅当您的正则表达式在字符串中的任何位置包含单个小写字母或数字时,您现有的正则表达式才匹配;建议说每个字符都必须是。
Alternatively you can use a slight variation to your regex: /[^a-z\d]/i
which matches a single non-alphanumeric value. Then tweak your logic to say: if I have a match here, then the string is invalid.
或者,您可以对正则表达式稍作修改:/[^a-z\d]/i
匹配单个非字母数字值。然后调整你的逻辑说:如果我在这里匹配,那么字符串无效。
As far as match
being undefined goes, read up on the regex-related methods in JavaScript. Some belong to strings, some belong to the Regexp
class.
至于match
未定义,请阅读JavaScript 中与正则表达式相关的方法。有些属于字符串,有些属于Regexp
类。
回答by matt3141
Use
用
reg_password1.match(letters)
回答by scunliffe
your jQuery .val();
method will return you the value, thus change this line
您的 jQuery.val();
方法将返回您的值,因此更改此行
if(!reg_password1.value.match(letters))
to
到
if(!reg_password1.match(letters))
I'm guessing you want a slightly different regex too.
我猜你也想要一个稍微不同的正则表达式。
If all characters must be a-z or 0-9 (case insensitive) then try this:
如果所有字符都必须是 az 或 0-9(不区分大小写),请尝试以下操作:
/^[a-z0-9]*$/i
However, that all said if this is truly for a password field, you should let the user choose symbols like $,#,!,@,%_,-,(,[,),] etc. to enable them to choose a strong password. ;-)
但是,总而言之,如果这确实是用于密码字段,您应该让用户选择诸如 $,#,!,@,%_,-,(,[,),] 等符号,使他们能够选择一个强密码。;-)