将输入设为无效 [英] Set input as invalid
问题描述
我有两个输入,例如
pass: <input type="password" name="pass" required/>
pass again: <input type="password" name="pass2" required/>
,我想比较这些输入,如果它们匹配,则将输入设置为有效.我试过了,但是我认为prop('valid', true);
不起作用:
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:
$(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
推荐答案
In the HTMLInputElement interface, there is no such property as valid
or invalid
.
您可以使用 setCustomValidity(error)
方法带有本地表单验证.
You can use the setCustomValidity(error)
method with native form validation.
关于您的脚本,以下是一个演示示例,该演示应在所有符合HTML5的浏览器中运行:
As for your script, here's a demo that should work in all HTML5 compliant browsers:
$('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>
这篇关于将输入设为无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!