【问题标题】:jquery.validate: Multiple Remote Rulesjquery.validate:多个远程规则
【发布时间】:2012-10-28 08:30:32
【问题描述】:

我计划使用两个远程规则验证单个文本字段。更像这样。

$('#form').validate({
   rules:{
      remote: 'url1.php',
      remote: 'url2.php'
   },
   messages:{
      remote: 'Error1',
      remote: 'Error2'
   }
});

这可能吗?我想要两个远程规则的单独错误消息。

希望能得到一些帮助!

【问题讨论】:

    标签: jquery validation


    【解决方案1】:

    首先我要说的是,据我所知,您必须将验证方法嵌套在某个属性下——您不能只将它们放在全局范围内。这将使您的代码如下所示:

    $('#form').validate({
       rules:{
          attribute1: {
            remote_check_1: true,
            remote_check_2: true
          }
       },
        messages:{
          attribute1:{
            remote_check_1: 'Error1',
            remote_check_2: 'Error2'
          }
        }
    
    });
    

    我不知道您是否可以将两者都放在规则对象下并为它们引发不同的错误消息。

    您可以做的是创建两个自定义验证函数,每个函数都有不同的名称。结果如下:

    $.validator.addMethod(
        "remote_check_1",
        function(value, element) {
          res = $.ajax({url: 'url1.php', data: { attribute1: value }, dataType: 'json'});
        return res;
        }
     );
    
    
    
    $.validator.addMethod(
            "remote_check_2",
            function(value, element) {
              res = $.ajax({url: 'url2.php', data: { attribute1: value }, dataType: 'json'});
            return res;
            }
         );
    

    【讨论】:

      【解决方案2】:

      jquery.validation 不支持单个字段中的多个远程验证。

      但是您可以通过合并服务器端的验证处理程序来合并两个远程验证。

      【讨论】:

        【解决方案3】:

        $.validator.addMethod("remote_check_1", function(value, element) { var data; $.ajax({ url: 'url1.php', type: 'post' data: { attribute1: value }, dataType : 'json', async: false, 成功: function(res) { data = res } }); return data; });

        $.validator.addMethod("remote_check_2", function(value, element) { var data; $.ajax({ url: 'url.php', type: 'post' data: { attribute1: value }, dataType : 'json', async: false, 成功: function(res) { data = res } }); return data; });

        【讨论】:

        • 欢迎来到 StackOverflow!请格式化代码并提供解释,以改进您的答案并使社区更容易理解
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多