Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alert when html5 validation fails

So what I need is simply an alert to appear when my html5 validation fails, like :

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

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

This seems really basic, but I couldn't find anything online about it. All I can find are ways to change the pop up message that appears directly on the field.

I need this because my forms spans over multiples tabs, so the bubble displaying an error message may not always appear depending on where the user is when he submits the form.

like image 839
CoqPwner Avatar asked Jul 16 '15 13:07

CoqPwner


People also ask

How do I bypass HTML5 validation?

To ignore HTML validation, you can remove the attribute on button click using JavaScript. Uer removeAttribute() to remove an attribute from each of the matched elements.

Does HTML5 have form validation?

Form validation can happen on the client side and the server side. Client side validation occurs using HTML5 attributes and client side JavaScript.

How does HTML5 validation work?

HTML5 validation kicks in when the form is submitted (user clicks the Submit button). When this happens, the browsers starts going through its list of required inputs and prompts when the input is missing on the required inputs.


2 Answers

There's invalid event fired on inputs if they don't pass validation: https://developer.mozilla.org/en-US/docs/Web/Events/invalid

Using jQuery you could do something like this:

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

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

like image 69
pawel Avatar answered Oct 17 '22 07:10

pawel


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>
like image 5
Junaid Anwar Avatar answered Oct 17 '22 07:10

Junaid Anwar