Form Validation Snippets: Email Validation with jQuery
With jQuery, it’s possible to write code that executes client-side validations for your forms and input fields. A common validation to make is to check whether or not an email address that’s entered into an email field is actually a valid email address (or at least in valid email address format). The following is a great snippet to use to perform your own client side email input validation without having to use a plugin:
(function($) { $.fn.validateEmail = function() {Â Â Â Â return this.each(function() {Â Â Â Â Â Â var $this = $(this);Â Â Â Â Â Â $this.change(function() {Â Â Â Â Â Â Â Â var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;Â Â Â Â Â Â Â Â if ($this.val() == "") {Â Â Â Â Â Â Â Â Â Â $this.removeClass("badEmail").removeClass("goodEmail")Â Â Â Â Â Â Â Â } else if (reg.test($this.val()) == false) {Â Â Â Â Â Â Â Â Â Â $this.removeClass("goodEmail");Â Â Â Â Â Â Â Â Â Â $this.addClass("badEmail");Â Â Â Â Â Â Â Â } else {Â Â Â Â Â Â Â Â Â Â $this.removeClass("badEmail");Â Â Â Â Â Â Â Â Â Â $this.addClass("goodEmail");Â Â Â Â Â Â Â Â }Â Â Â Â Â Â });Â Â Â Â });Â Â }; })(jQuery);
The snippet above assigns the class “goodEmail†to a submission that’s in email format ([email protected]) and “badEmail†to submissions that aren’t, and if the .badEmail class is applied to the submission, it won’t be validated and the form will not submit.