Form Validation Snippets: Email Validation with jQuery (by Learning 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 (example@example.example) 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.

Bir Cevap Yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir

TOP