javascriptjqueryhtmlformspreventdefault

Check Required Fields With preventDefault


I ran into a situation where I have a HTML form and it has required on many of the fields. The issue is I have to use preventDefault which ignores 'required' inputs and submits the form even without the required fields. Because the work is not entirely up to me I must use preventDefault and work around it.

I am working with jQuery and I am trying to find a way to target the fields that have required and prevent the form from submitting on click.It is important that the required fields are filled out on the form before a user can submit the form as I do not want required information missing when it is being submitted. Help is appreciated!

HTML

<form id="myForm">

    <input type="text" name="sentence1" id="st1" placeholder="Text here" required>

    <input type="text" name="sentence1" id="st2" placeholder="Text here" required>

    <input type="text" name="sentence1" id="st3" placeholder="Text here" required>

    <input type="text" name="sentence1" id="st4" placeholder="Text here" required>

    <input type="text" name="sentence1" id="st5" placeholder="This field is not required">

    <button type="submit" id="submit-form">Submit</button>

</form>

Solution

  • In your event handler, where you are using preventDefault(), add the checkValidity() method on the form element:

    document.getElementById('myForm').checkValidity();
    

    This will "statically" check your form for all HTML5 constraint violations (including required),