Link to home
Start Free TrialLog in
Avatar of Refael
RefaelFlag for United States of America

asked on

jQuery form validation on blur and on submit

Hello Experts,

I am writing a simple custom jQuery validation, example:


$(document).ready(function() {

var validEmail = new RegExp(/^(([^<>()[\]\\.,;:\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,}))$/);

$('#contactEmail').blur(function() {
						
	if($(this).val().match(validEmail)) {

	    $(this).removeClass("error");			
	    } else {
	    $(this).addClass("error");
	}	
 });
});

Open in new window


I need to use the same for "on submit". Do i need to write the same code twice one for .blur and the other for .submit or is it possible to combine both?

Thank you for your help!
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Test page : http://jsfiddle.net/6jcZS/
$(document).ready(function() {

    var validEmail = new RegExp(/^(([^<>()[\]\\.,;:\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,}))$/);

    var validateEmail = function(evt) {
        if($(this).val().match(validEmail)) {
            $(this).removeClass("error");
        } else {
            $(this).addClass("error");
            evt.preventDefault();
        }
    }

    $('#contactEmail').blur(validateEmail);
    $("#submitButtonID").click(function(evt) {
        validateEmail.call($('#contactEmail'),evt);
    });
});

Open in new window

Avatar of Refael

ASKER

Hi leakim971 :-)

Always thank you,

If i have more validations i should simply add "evt" to their function and it will stop the form from submitting until all the conditions have met?
Avatar of Refael

ASKER

Hi leakim971 :-)

I am trying that out. it seem to work perfect yet this function is having a problem.

var requiredInput = $("#contactform input[inputRequired]");

var validateRequired = function(evt) {
	
	$(requiredInput).each(function() {
					
		if (($.trim($(this).val() )=== "") || ($.trim($(this).val()).length <= 5)) {
							
			$(this).addClass("error");
			evt.preventDefault();
			
		} else {

			$(this).removeClass("error");
			$(this).next().text("");
		}
	});
}

$(requiredInput).blur(validateRequired);

$("#submit").click(function(evt) {

   validateRequired.call($(requiredInput),evt);

}

Open in new window

Avatar of Refael

ASKER

Hi eakim971

Can you please help me resolve this. The only problem when applying your solution as in the example in the above comment is that all the required field are highlighted once i "blur" on any of the form fields. Thanks.
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial