jQuery 将输入设置为无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18128882/
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
Set input as invalid
提问by Lubos K.
I have two inputs, e.g.
我有两个输入,例如
pass: <input type="password" name="pass" required/>
pass again: <input type="password" name="pass2" required/>
and I want to compare these inputs, and if they match, set input as valid. I tried this, but I think that prop('valid', true);
does not work:
我想比较这些输入,如果它们匹配,则将输入设置为有效。我试过这个,但我认为这prop('valid', true);
不起作用:
$(document).ready(function() {
$('input[name=pass2]').keyup(function() {
if($('input[name=pass]').val() == $('input[name=pass2]').val()) {
$('#pass_hint').empty();
$('#pass_hint').html('match');
$(this).prop('valid', true);
} else {
$('#pass_hint').empty();
$('#pass_hint').html('mismatch');
$(this).prop('invalid', true);
}
});
});
I create a registration form and if passwords are not the same, input field is invalid and I can′t submit this and show me some hint. ...and I don′t know how I set this input as invalid
我创建了一个注册表单,如果密码不一样,输入字段无效,我不能提交这个并给我一些提示。...我不知道我如何将此输入设置为无效
回答by rink.attendant.6
In the HTMLInputElement interface, there is no such property as valid
or invalid
.
在HTMLInputElement 接口中,没有valid
或 之类的属性invalid
。
You can use the setCustomValidity(error)
method with native form validation.
您可以将该setCustomValidity(error)
方法与本机表单验证一起使用。
As for your script, here's a demo that should work in all HTML5 compliant browsers:
至于你的脚本,这里有一个可以在所有 HTML5 兼容浏览器中工作的演示:
$('input[name=pass2]').keyup(function () {
'use strict';
if ($('input[name=pass]').val() === $(this).val()) {
$('#pass_hint').html('match');
this.setCustomValidity('');
} else {
$('#pass_hint').html('mismatch');
this.setCustomValidity('Passwords must match');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action='#'>
<p>Password:
<input name=pass type=password required>
</p>
<p>Verify:
<input name=pass2 type=password required>
</p>
<p id=pass_hint></p>
<button type=submit>Submit</button>
</form>