javascript Jquery,如何知道输入何时有:无效选择器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14384593/
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-10-26 21:29:52  来源:igfitidea点击:

Jquery, how to know when input have a :invalid selector?

javascriptjqueryvalidation

提问by Sergio Flores

I have this code:

我有这个代码:

HTML

HTML

<input type="text" data-value="1" data-type="input-records" placeholder="Value" pattern="\d{1,4}$" />

CSS

CSS

input[type=text]:invalid { background-color: red; }

Javascript

Javascript

$("[data-type=input-records]").die().live("keypress", function (e) {
    if (!($(this).val().length + 1) < 5) {
        e.preventDefault();
        return;
    }

    // More code below...
});

I want to make a validation like this:

我想进行这样的验证:

if (!$(this).hasSelector(":invalid")) {
    showMessage("Invalid value");
}

回答by Andrew Whitaker

Use the isfunction to test for the :invalidpseudoclass:

使用is函数测试:invalid伪类:

if ($(this).is(":invalid")) {
    showMessage("Invalid value");
}

Example:http://jsbin.com/ikuwur/2/edit

示例:http : //jsbin.com/ikuwur/2/edit