【问题标题】:add rule to jQuery validate from code behind从后面的代码向 jQuery validate 添加规则
【发布时间】:2012-12-04 12:19:44
【问题描述】:

我知道要使用 jQuery 添加验证器,您需要执行以下操作:

 $(document).ready(function() {
            $("#form1").validate({
                rules: {
                    <%=txtUserName.UniqueID %>: {
                    maxlength: 5,
}

但是我将如何从后面的代码中添加规则,例如将所需的规则添加到文本框。

我该怎么做呢?

提前致谢。

【问题讨论】:

    标签: c# jquery asp.net jquery-plugins


    【解决方案1】:

    一种方法是使用后面代码中的函数生成整个规则参数,例如在页面上您将拥有:

     $(document).ready(function() {
            $("#form1").validate(<%=GetValidationRules()%>); 
    

    然后在后面的代码中添加一个函数,GetValidationRules,它返回的参数包含所有要验证的控件的规则。

    【讨论】:

      【解决方案2】:

      要向元素添加规则,您可以尝试

      $("#input_ID").rules("add", "required"); // input_ID is element's id
      

      上面的行会将required 规则添加到ID 为input_ID 的元素中。但在这种情况下,您必须先致电$("#form1").validate();,并且您已经拥有它。你也可以使用

      $("#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"
              }
          }
      });
      

      以上代码将name 元素指定为required,将email 元素指定为required 和有效的电子邮件地址。为name 元素指定了一条消息,为email 指定了两条消息。这里,nameemail 是两个元素的名称。

      Read More.

      【讨论】:

      • 谢谢你,但我想从后面的代码中添加一条规则,这就是我的目标。
      • 好了,基本上我是想动态创建一个控件,然后创建一个规则让控件成为必填字段。这基本上就是我想做的。
      【解决方案3】:

      通过使用 StringBuilder 构建字符串查询然后在页面上注册脚本来解决这个问题:

      ScriptManager.RegisterClientScriptBlock
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-02
        • 1970-01-01
        • 2010-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多