[英]jQuery validation plugin
I am using jQuery validation plugin to validate my form on client side. 我正在使用jQuery 验证插件在客户端验证我的表单。 I am adding a new method using addMethod function for every HTML control which have regex (custom) attribute.
我为具有regex(自定义)属性的每个HTML控件添加了一个使用addMethod函数的新方法。 My HTML control would look like.
我的HTML控件看起来像。
<input type="text" id="txtInf" name="txtInf" regex="some regular exp" error="check your inf"></input>
$("*[regex]").each(function () {
var controlId = $(this).attr('name');
var regex = new RegExp((this).attr('regex'));
var error = $(this).attr('error');
$.validator.addMethod(controlId, function (value, element) {
return this.optional(element) || false;
}, error);
$(this).rules("add", { '" + controlId + "': "^[a-zA-Z'.\s]{1,40}$" });
$(this).validate();
});
Here I am giving method name as controlId which is txtInf . 在这里,我将方法名称指定为controlId ,即txtInf 。 In below line, I need to give txtInf, but I want to use controlId variable instead, as I want to make this function a generic one.
在下面的代码行中,我需要提供txtInf,但是我想使用controlId变量,因为我想将此函数设为通用函数。 But if I write controlId directly, it searches for the method with the same.
但是,如果我直接编写controlId,它将搜索相同的方法。 But added method is txtInf actually.
但是添加的方法实际上是txtInf。 So I need some way to generalise this line by using controlId variable.
因此,我需要一些方法通过使用controlId变量来概括这一行。
$(this).rules("add", {txtInf: "^[a-zA-Z'.\s]{1,40}$" });
The problem is that you can't use a variable name for referencing in an object literal. 问题是您不能使用变量名来引用对象文字。 What I've done in the past when I need to do something like this is to manually create the JSON string and pass it through parseJSON.
过去我需要做类似的事情是手动创建JSON字符串并将其通过parseJSON传递。 this would look something like:
这看起来像:
$(this).rules("add", $.parseJSON('{"' + controlId + '":"^[a-zA-Z\'.\s]{1,40}$" }');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.