Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 799
user5854648 Avatar asked Feb 16 '26 23:02

user5854648


2 Answers

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),

like image 193
Randy Casburn Avatar answered Feb 18 '26 13:02

Randy Casburn


Came across the same problem and here is the solution that works for me.

Form elements have a function called checkValidity and reportValidity. We can use these and override the click event for the submit button.

$('#submit-form').click((event) => {
    let isFormValid = $('#myForm').checkValidity();
    if(!isFormValid) {
        $('#myForm').reportValidity();
    } else {
        event.preventDefault();
        ... do something ...  
    }
});
like image 33
jezztify Avatar answered Feb 18 '26 13:02

jezztify



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!