繁体   English   中英

RegEx用于jQuery输入验证

[英]RegEx for jQuery Input Validation

我正在使用jquery验证插件来验证我的输入字段。

我有一个应该接受的领域:

a)字母[a-zA-Z]

b)带数字的字母[a-zA-Z0-9]

c)没有特殊字符

所以:

ADFad1334或43545SFDDFdf454fgf:正确,因为我们有字母和数字

asdadadASD:是正确的,因为我们只有字母

12312342:不正确,因为它只有数字

sdff23424#$:不正确,因为有特殊字符(在此示例中为#和$)

我使用的代码如下:

$.validator.addMethod("atLeastAletter", function(value) {
 return     /^[a-zA-Z]*$/img.test(value) || /^[a-zA-Z0-9]*$/img.test(value); 

},"Must contain at least a letter and/or number(s). No other characters are allowed");

接着:

$('#RegistrationForm').validate({

    rules:  {
                fieldname:  {
                                atLeastAletter: true

                            },

             .....

此正则表达式的问题在于,如果输入仅是数字(例如3434224),它将接受并通过验证。

问题是什么?

提前致谢。

/^\w*[a-zA-Z]+\w*$/

该字符串应与仅包含字母和数字的任何字符串匹配,但必须至少包含一个字母。

sadAddsa  // Pass
98463298  // Fail
jdsH98sd  // Pass
987Fkjd89  // Pass
jfk!jhj  // Fail
kjhgh8768!@  // Fail
A8  // Pass
8S  // Pass
B  // Pass
7  // Fail
B_bkfd86jh // Fail (Using the regex in the edit)

编辑:正如阿尔法·布拉沃指出的那样。 这也将与下划线匹配。 如果您不想使用下划线,则/^[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*$/仅匹配字母和数字,除非包含一个字母。

或这种模式

^(?=\S*[a-zA-Z])[a-zA-Z0-9]+$  

演示版

^               # Start of string/line
(?=             # Look-Ahead
  \S            # <not a whitespace character>
  *             # (zero or more)(greedy)
  [a-zA-Z]      # Character Class [a-zA-Z]
)               # End of Look-Ahead
[a-zA-Z0-9]     # Character Class [a-zA-Z0-9]
+               # (one or more)(greedy)
$               # End of string/line

如果您想使用所有HTML5,请查看以下小提琴: http : //jsfiddle.net/bud68oho/2/

该小提琴使用required和pattern属性来验证表单。 如果未填写输入,则required属性不允许表单发布pattern属性允许您实现用于匹配的正则表达式。 如果输入不符合正则表达式的要求,则该表单将不会发布。

使用此方法的唯一陷阱是浏览器兼容性。 确保使用目标浏览器测试此方法。 上面的示例适用于最新版本的IE和Chrome,我无法进行任何进一步的测试。

/^[a-zA-Z0-9]*$/img.test("1")为true,因此只需使用两个正则表达式即可:

return /^[a-zA-Z]*$/img.test(value) || (/[a-zA-Z]/img.test(value) && /^[a-zA-Z0-9]*$/img.test(value))

或像这样:

return /^[a-zA-Z]*$/img.test(value) || (/^[a-zA-Z0-9]*$/img.test(value) && !/^[0-9]*$/img.test(value))

注意:如果将i放在正则表达式(img)后面,则只需要加上a或AZ,就不区分大小写。 注意:您可以在这些正则表达式中使用空字符串“”。

我认为您可能需要对仅数字的情况进行正字母数字检查和负检查。

$.validator.addMethod("atLeastAletter", function(value) {
  return     /^[a-zA-Z0-9]+$/img.test(value) && ! /^[0-9]+$/img.test(value)

},"Must contain at least a letter and/or number(s). No other characters are allowed");

暂无
暂无

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

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