[英]add rule to jQuery validate from code behind
I know that to add a validator with jQuery you would do something like this: 我知道要使用jQuery添加验证器,您将执行以下操作:
$(document).ready(function() {
$("#form1").validate({
rules: {
<%=txtUserName.UniqueID %>: {
maxlength: 5,
}
But how would I add to the rules from the code behind, say for example add the required rule to the textbox. 但是我如何从后面的代码中添加规则,例如将所需的规则添加到文本框中。
How would I go about doing that? 我将如何去做?
Thanks in advance. 提前致谢。
One approach would be to produce the entire rules parameter using a function in the code behind, so for example on the page you would have: 一种方法是使用后面代码中的函数来产生整个规则参数,例如,在页面上您将具有:
$(document).ready(function() {
$("#form1").validate(<%=GetValidationRules()%>);
and then add a function in the code behind, GetValidationRules that returns the parameter containing the rules for all controls to be validated. 然后在后面的代码GetValidationRules中添加一个函数,该函数返回包含要验证的所有控件的规则的参数。
To add a rule to an element you can try 要向元素添加规则,您可以尝试
$("#input_ID").rules("add", "required"); // input_ID is element's id
Above line will add the required
rule to an element with id input_ID
. 上面的行会将
required
规则添加到ID为input_ID
的元素中。 But in this case you have to call $("#form1").validate();
但是在这种情况下,您必须调用
$("#form1").validate();
first and you have it already. 首先,您已经拥有它。 Also you can use
你也可以用
$("#form1").validate({
rules: {
name: "required",
email: {
required: true,
email: true
}
},
messages: {
name: "Please specify your name",
email: {
required: "We need your email address to contact you",
email: "Your email address must be in the format of name@domain.com"
}
}
});
Above code specifies a name
element as required
and an email
element as required
and a valid email address. 上面的代码指定一个
name
为元素required
和email
的元素required
和有效的电子邮件地址。 A single message is specified for the name
element, and two messages for email
. 为
name
元素指定了一条消息,为email
指定了两条消息。 Here, name
and email
are name of two elements. 在此,
name
和email
是两个元素的名称。
通过使用StringBuilder建立字符串查询,然后使用以下命令在页面上注册脚本,即可解决此问题:
ScriptManager.RegisterClientScriptBlock
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.