jQuery element.setCustomValidity 似乎不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33456300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:57:23  来源:igfitidea点击:

element.setCustomValidity does not seem to work

jqueryhtmlformsvalidationdom

提问by pachyderm94

I have a change event on an email field that is supposed to validate that the email address is unique using an ajax call. The problem is that it is telling me that the element does not support the setCustomValidity method. Please Help.

我在电子邮件字段上有一个更改事件,该事件应该使用 ajax 调用验证电子邮件地址是否唯一。问题是它告诉我该元素不支持 setCustomValidity 方法。请帮忙。

$("#tbEmail").change(function (event) {
    var obj = new Object();

    obj.email = $("#tbEmail").val();
    var params = JSON.stringify(obj);

    $.ajax
    (
        {
            type: "POST",
            url: "./controllers/Consumer.aspx/validateEmail",
            data: params,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (result) {
                if (result.d != 0) {

                    var element = $("#tbEmail");
                    element.setCustomValidity('The email address entered is already registerd.');
                    alert(element.checkValidity());
                    alert(element.validationMessage);
                }
                else {
                    $("#tbEmail").setCustomValidity("");
                };
            },
            error: function (result) { ProcessError(result) }
        }
    );

})

回答by vinayakj

setCustomValidityis DOM API not jQuery API. In your code you are trying to call it on jQuery instance. So you need to first get the DOM element instance & then call the API.

setCustomValidity是 DOM API 不是 jQuery API。在您的代码中,您试图在 jQuery 实例上调用它。所以你需要先获取DOM元素实例,然后调用API。

Also it needs to be HTML5 compliant browser and a form.

它还需要是 HTML5 兼容的浏览器和表单。

 var element = $("#tbEmail")[0];
 element.setCustomValidity('The email address entered is already registerd.');

回答by Paulo Henrique

A simpler approach to this, adding "[0]":

一个更简单的方法,添加“[0]”:

$("#tbEmail")[0].setCustomValidity("")

回答by AmirHossein Manian

use get(0).

使用get(0).

    var element = $("#tbEmail").get(0);
    element.setCustomValidity('The email address entered is already registerd.');

回答by NGaneshan

$("#tbEmail").setCustomValidity("Error msg")

$("#tbEmail").setCustomValidity("错误信息")