javascript - Jquery 自定义验证器 - 检查值是否有效?

标签 javascript jquery validation

我创建了一个像这样的 Jquery 自定义验证器

        var response;
    $.validator.addMethod(
        "uniqueUserName",
        function (value, element) {

            $.ajax({
                type: "POST",
                url: "/umbraco/surface/MemberShipSurface/ValidatePostCode",
                data: JSON.stringify({ PostCode: value }),
                contentType: "application/json; charset=utf-8",
                success: function (msg) {
                    alert(msg.istrue);
                    response = msg.istrue;

                }
            });
            return response;
        },

        "wrong postcode"
    );
    $("#reg-form").validate({
    rules: {
        day: {
            required: true,
            range: [01, 31]
        }, 
        PostCode: {
            required: true,
            number: true,
            maxlength: 4,
            minlength: 4,
            uniqueUserName: true
        }
    },

    errorElement: "span",

    submitHandler: function (form) {      
    }
});

如果 ajax 的输出为真,则表示验证成功,我们不需要显示任何错误消息,否则显示错误消息。但是现在我首先在表格上输入的任何值都显示为错误,从第二次开始它显示验证成功。谁能指出我在这里做错了什么?

最佳答案

remote-method可用你可以像这样使用它,

rules: {
    day: {
        required: true,
        range: [01, 31]
    },            
    PostCode: {
      required: true,
      number: true,
      maxlength: 4,
      minlength: 4,
      remote: {
        url: "/umbraco/surface/MemberShipSurface/ValidatePostCode",
        type: "post",
        data: {
          PostCode: function() {
            return $( "#PostCode" ).val();
          }
        }
      }
    }
}

如果您想使用自定义方法,请在 $.ajax() 中使用 async=false像这样打电话

var response=false;
$.ajax({
    type: "POST",
    async:false,// now it will wait until you get response
    url: "/umbraco/surface/MemberShipSurface/ValidatePostCode",
    data: JSON.stringify({ PostCode: value }),
    contentType: "application/json; charset=utf-8",
    success: function (msg) {
        response = msg.istrue;
    }
});
return response;

关于javascript - Jquery 自定义验证器 - 检查值是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43751595/

相关文章:

javascript - 无法通过其 ID 找到 <path> 元素

javascript - jQuery 单击处理程序仅触发一次

javascript - 如何测试 angular 指令的 templateUrl 指向的 HTML?

javascript - 当js设置源时检查图像是否加载?

javascript - 从另一个动态html的值设置输入框的max属性

java - 将新对象附加到 Wicket 中的自定义 validator

javascript - 在我的函数中更改 css 背景颜色

javascript - 如何为点击添加值(value)

javascript - 打开基于ajax响应的jquery-ui对话框

javascript - 如何检查一个对象中的所有数字是否在某个范围内?