简体   繁体   中英

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() ?

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 .

您可以在表单元素中使用novalidate属性:

<form method="post" action="..." novalidate>...</form>

This is what I did now and what worked (using jQuery, where $form represents the ):

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

There is a specific method for handle a "submit". Here's here !

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