Skip to content
Advertisement

How to intercept HTML5 input validation with JavaScript?

<form ... onsubmit="return false">
   <input type="text" name="location" ...>
   <input type="url" ... required>
   ...
</form>

Now, if I enter a location and hit ENTER, the browser tells me that an URL is required which is not an expected or desired outcome. The ENTER should just be ignored.


Question

How can I prevent the browser from checking the required field after hitting ENTER in the “location” input field and only let the browser check the “url” field when submitting the form with JavaScript using form.submit()?

Advertisement

Answer

You need to stop the default behavior of enter button for your form elements.

Lets have an example:

HTML5 form as

<form id="form">
  <input type="text" name="test1" id="test1" required/>
  <input type="text" name="test2" id="test2" required/>
  <input type="submit" value="Test"/>
</form>

Then apply below code

$(document).ready(function() {
  $(form).find('input').on('keydown', function(e){
     if(e.which == 13) // KEY.ENTER = 13
       e.preventDefault();
  });
});

Based on above scenario, here is the fiddle.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement