触发无效事件jquery

时间:2016-11-07 14:43:33

标签: jquery html forms input

可以"无效的弹出窗口"由自定义函数触发而不提交表单?

弹出广告无效 - > https://www.html5rocks.com/static/images/tutorials/constraintvalidation/ChromeForAndroid.png

enter image description here

1 个答案:

答案 0 :(得分:0)

假设您有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验证。