0

I was using the JQuery Validation plugin, but unfortunately it does not work well with another plugin I am using. Therefore, I am now writing my own custom validation. At the moment I have something like this

function doValidation(formData, jqForm, options) {

    var fullName = $.trim($("#fullName").val());
    var emailAdd = $.trim($("#emailAdd").val());
    var aNum = $.trim($("#aNum").val());

    if(fullName.length == 0) {
        alert("Please enter your full name");
        return false;
    }

    if(fullName.length > 50) {
        alert("Name is to long");
        return false;
    }

    if( !validateEmail(emailAdd)) {
        alert("Invalid email");
        return false;
    }
}

function validateEmail($email) {
    return /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test($email);
}

Now obviously I don't want to alert the errors, this is for testing. I also don't want to return false on all of them.

What I am looking to do is add all the errors to an array or something, because if validation fails I need to display all of the errors. I also need to return false if validation fails so my form does not submit. Each input may have more than one validation rule, but only one will be triggered at any time.

How would I go about doing this? I am looking to append all errors to a div with an id validation-results.

Any advice appreciated.

Thanks

1 Answer 1

1

You can store the messages in an array:

function doValidation(formData, jqForm, options) {
    var errors = [];    

    var fullName = $.trim($("#fullName").val());
    var emailAdd = $.trim($("#emailAdd").val());
    var aNum = $.trim($("#aNum").val());

    if(fullName.length == 0) {
        errors.push("Please enter your full name")
    }

    if(fullName.length > 50) {
        errors.push("Name is to long")
    }

    if(!validateEmail(emailAdd)) {
        errors.push("Invalid email")
    }
    if (errors.length > 0) {
        $('#validation-results').html(errors.join('<br>'));
        return false;
    }    
    return true;
}

Now, to avoid form execution:

You can get the form and according to the results o validation method you send or not.

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.