我在 HTML5 输入中使用模式属性。它工作正常,直到我使用 setCustomValidity 添加自定义消息。所有这一切应该做的是
Sets the validationMessage property of an input element.
但是我的模式被忽略了。如果我注释掉 setCustomValidity,该模式就会起作用。
HTML
<form>Country code:
<input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">
</form>
JS
$('input').get(0).setCustomValidity("It's wrong");
$('input').on('input', function () {
console.log($(this).prop('validity'));
var valid = $(this).get(0).checkValidity();
console.log(valid); });
最佳答案
使用reportValidity();
代替checkValidity();
,并且在调用该函数时首先使用空字符串清除有效性!
$('input').get(0).setCustomValidity("It's wrong");
$('input').on('input', function () {
this.setCustomValidity('');//Add this!!
console.log($(this).prop('validity'));
var valid = $(this).get(0).reportValidity();//here
console.log(valid); });
编辑
让它在这个 fiddle 中工作:http://jsfiddle.net/hrtsz50s/1/
关于javascript - 设置自定义 HTML5 有效性消息属性会忽略模式正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32829776/