[英]jQuery Validate regex in HTML5
Im using jQuery validate to validate a front end form. 我正在使用jQuery validate来验证前端表单。 I ideally want the regex to be picked up from the HTML5
pattern
attribute on the input field. 理想情况下,我希望从输入字段的HTML5
pattern
属性中提取正则表达式。
I have a working version using the following code: 我有一个使用以下代码的工作版本:
function isUKPostcode(value){
return /^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$/.test(value);
}
$.validator.addMethod("postcode", function(value, element){
return this.optional(element) || isUKPostcode(value);
}, "Please enter a valid UK postcode");
But ideally I would like to set it up with simply: 但理想情况下,我想简单地设置它:
<input id="Inputfield_user_first_name" class="postcode" name="user_first_name" type="text" maxlength="60" pattern="([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)">
The same way that attributes such as required
and maxlength
are automatically picked up by $.validate()
$.validate()
自动获取诸如required
和maxlength
类的属性的方式相同
Does anyone know if this is possible? 有人知道这是否可能吗?
As a workaround, I came up with the following code to check the pattern
attribute and set a custom message during validator.addMethod()
. 作为一种解决方法,我提出了以下代码来检查
pattern
属性并在validator.addMethod()
期间设置自定义消息。
$o.validator.addMethod("regex", function(value, element){
var pattern = $o(element).prop('pattern');
if(!pattern || this.optional(element)){
return true;
}
return new RegExp(pattern).test(value);
}, $o.validator.format("{0}"));
$o.validator.addClassRules("visible-postcode-input", {
regex: "Please enter a valid UK postcode",
});
There is no need to write a custom method. 无需编写自定义方法。
You simply need to include the additional-methods.js file . 您只需要包括Additional-methods.js文件 。 It includes the
pattern
method which will pickup the HTML5 pattern
attribute automatically. 它包括
pattern
方法,该方法将自动提取HTML5 pattern
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.