Html5 validation failure warning

So what I need is just a warning to appear when my html5 validation fails, e.g .:

alert("Error, please fill all required fields before submitting.");

      

Is there some event that I could use to show this warning using JavaScript or jQuery?

This seems to be really basic, but I couldn't find anything on the internet. All I can find are ways to change the popup message that appears directly in the box.

I need this because my forms span multiple tabs, so the error message bubble may not always show depending on where the user is when they submit the form.

+3


source to share


4 answers


There invalid

event is triggered on inputs if they fail validation: https://developer.mozilla.org/en-US/docs/Web/Events/invalid

Using jQuery you can do something like this:



$('input[required]').on('invalid', function(e){
  alert("Error, please fill all required fields before submitting.");
});

      

http://jsfiddle.net/644Lou8k/1/

+8


source


For those who don't want to use jQuery:



var requiredInput = document.getElementById('requiredField');

function showAlert(){
  alert("Error, please fill all required fields before submitting.");
}

requiredInput.addEventListener("invalid", showAlert, false);
      

<form action="">
  <input id="requiredField" type="text" placeholder="Required input" required>
  <button type="submit">Submit</button>
</form>
      

Run code


+1


source


You can capture the form submit event with javascript and validate / validate the values ​​before allowing it to pass.

$('form').submit(function () {
  if($('#blah').val() == "") {
    alert('blahblah');
    return false;
  }
});

      

-1


source


HTML5 validation starts when the user submits the form and does not raise any event. The only way is for your own JS validation, like many others, to be mentioned in their answers. Here is a good HTML5 answer required for validation not to work

The HTML5 form validation process is limited to situations where the Form is submitted via a submit button. The form submission algorithm explicitly says that validation fails when the form is submitted via the submit () method. Apparently the idea is that if you are submitting a form via JavaScript you should be doing Validation

-1


source







All Articles