Xeen Xeen - 2 months ago 6
jQuery Question

How to correctly validate form with jQuery?

So I have this jQuery for my form:

frm.submit(function(event) {


if(validateForm()) {
} else {


It does sort of work, but I get JS
(and it doesn't say anything else in the console about it), I think the reason is that the function has to go through the validation again? Kind of like a circular dependency.

Can you show me a better way to do the exact thing that I'm trying to achieve here please?

  1. Validate and show errors if filled in the wrong way;

  2. Submit the form if everything is ok


Something like this maybe?


<input type="text" id="name" />
<input type="tel" id="phone" />
<div id="submit">Submit</div><br>
<div id="errors"></div>

JS -

var user = {}

    // validating form

    if(!$('#name').val()) {
        $('#errors').text('invalid value in "name" field')
        return false;

    if(!$('#phone').val()) {
        $('#errors').text('invalid value in "phone" field')
        return false;

    user.phone = $('#phone').val();
    user.name = $('#name').val();

    // form submission goes here


The logic -
once a function returns anything (true, false, a string, you name it), the execution of anything else after the return itself, is prevented.
If you don't use any kind of return, functions default to returning true, which means the JS code will keep on to the next function\declaration.

This gives you the option of manipulating elements and handle errors just before returning false and stopping the function from continuing to run.