jquery.validate: 多个远程规则

3

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

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

这是可能的吗?我希望针对这两个远程规则有单独的错误消息。
希望能得到一些帮助!
3个回答

3

首先,据我所知,您必须将验证方法嵌套在特定属性下 - 您不能只将它们放在全局范围内。 这将使您的代码看起来像这样:

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

0

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

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


0
$.validator.addMethod("remote_check_1", function(value, element) { var data; $.ajax({ url: 'url1.php', type: 'post' data: { attribute1: value }, dataType: 'json', async: false, success: 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, success: function(res) { data = res } }); return data; });

1
欢迎来到StackOverflow!请格式化代码并提供解释,以改善您的答案并使其更易于理解社区。 - xKobalt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接