[英]Extending the HTML 5/JavaScript input validation API
我将在输入类型数字字段上使用 HTML 5 验证,该字段使用 min 和 step 属性以及初始值,即,
<input type="number" min="50" step="50" value="100" />
但是,我希望验证允许用户输入大于最小值但在步骤之间的值,此处以粗体显示:
50, 51 ... 99 , 100, 101 ... 149 , 150, 151 ...
我是否可以在验证 API 执行完其工作后以某种方式“挂钩”到它,并且如果它发现的唯一错误是步骤错误,请重置有效条件,以便可以提交该字段所在的表单?
如果除了消息字符串参数之外, element.setCustomValidity()
函数还可以接受回调函数,如果元素的值通过回调函数中的检查或返回非空消息,则肯定会很好如果值未通过,则为字符串。
您可以使用文本输入并使用使用正则表达式 (RegExp) 的模式属性来验证其值,如下所示:
<form>
<input type="text" pattern="(^[6-9][0-9]{1,}$|^[5][1-9]$)|(^((?!00|50|[a-zA-Z]).){3,}$)" title="Invalid values" required>
</form>
编辑 1:由于您不想更改输入类型,这可能是解决方案(使用相同的 RegEx):
<script>
window.validate50 = function(ev){
var tar = ev.target || ev;
// tests the value is not a 50 multiple
if(!/(^[6-9][0-9]{1,}$|^[5][1-9]$)|(^((?!00|50|[a-zA-Z]).){3,}$)/img.test(tar.value)){
// in this case triggers the validation using the text on html title attribute
tar.setCustomValidity(tar.title);
// returns false so the "submit" action is supressed
return false;
}
};
</script>
<form>
<input type="number" min="50" step="50" onchange="return validate50(this);" title="The number must not be a multiple of 50!" required>
</form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.