简体   繁体   中英

Trigger HTML5 validation using jQuery

Before creating this function when something was incorrect in inputs HTML5 was triggering default invalid action for browser (which was setting border color of input into red etc). But now, if entered value is invalid, it doesn't do anything on blur event. Can I trigger browser's default invalid action for input when if 's condition not met?

(function ($) {
    $.fn.isValid = function () {
        return document.getElementById(this[0].id).checkValidity();
    };
})(jQuery);
$(function () {
    $(".answer").blur(function () {
        if ($(this).isValid()) {
          //do something
        }
        else
         //trigger default invalid action
    })
});

Javascript/jQuery isn't necessary. You can utilize the :invalid CSS pseudo-class; this lets you apply a specific style to invalid elements. Similarly, valid elements match the :valid pseudo-class.

Source: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Data_form_validation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM