Ben Ben - 4 months ago 18
Ajax Question

Submit form via AJAX but keep client side validation

In my HTML code I have required fields and regular expression pattern checking using HTML5 attributes. I want to submit my data to my server via AJAX but I have to use e.preventDefault();

Using that, disables all the HTML5 attributes like "required" and "type=email" and the built in HTML5 client side check. Basically the user can just submit an empty form.

Is there a way to make HTML5 first check if the attributes i specified are met, then e.preventDefault from submitting so i can manually submit via AJAX?



$("input[type='submit']#input_submit").click(
function(e) {
//Prevents form from submitting right away:
e.preventDefault();

// Allows or keeps halting form submission process; returns true or false.
validationForm();
});

function validationForm() {

};

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="lastname">
<p>Last Name</p>
<input type="text" name="lastname" placeholder="Last Name" pattern="[a-zA-Z]+" title="Letters Only" required></input>
</section>
<input id="input_submit" type="submit" value="submit">




Answer

If you instead prevent the form submit from happening (instead of the button click), you will get the behaviour you want.

$("form#your_form").on("submit", function(e) {
    e.preventDefault();
    alert();
});

https://jsfiddle.net/4o8nnkjy/

So in the above example, the alert only happens if the form is valid.