假设你有一个input
<input type="text" id="input_id">
使用 jquery,您可以执行此验证:
$(document).on("keyup", "#input_id", function(){
if( $(this).val() == '' )
{
/* show error message here */
}
});
或者如果你想使用纯 JavaScript,你可以使用:
var el = document.getElementById('input_id');
el.addEventListener("keyup", function() {
validate_me(this);
}, false);
function validate_me(e)
{
if(e.value == '')
{
/* error message here */
}
}
如果您只需要 html5 解决方案:
要检查某个字段是否有效,请使用:
$('#myField')[0].checkValidity() // returns true/false
要检查表单是否有效,请使用:
$('#myForm')[0].checkValidity() // returns true/false
如果您想显示某些浏览器(例如 Chrome)的原生错误消息,不幸的是,唯一的方法是提交表单,如下所示:
var $myForm = $('#myForm')
if (!$myForm[0].checkValidity()) {
// If the form is invalid, submit it. The form won't actually submit;
// this will just cause the browser to display the native HTML5 error messages.
$myForm.find(':submit').click()
}
请记住,并非所有浏览器都支持 HTML5 验证。