1
\$\begingroup\$

A quick little method for validating form input with jQuery (and some built in bootstrap classes). I know the regex isn't perfect but it's close enough. Thoughts?

var validate = {

    email: function (emailAddress) {
        var re = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
        return re.test(emailAddress);
    },

    onInput: function (formSelector, responseSelector) {
        var $form = $(formSelector),
            $input = $(formSelector + ' input'),
            $feedback = $(responseSelector),
            _this = this;

        $input.on('input', function () {
            $(this).removeClass('warning');
            $feedback.removeClass('show').addClass('hidden');
        });

        $input.on('blur', function () {
            var $blur = $(this),
                type = $blur[0].type;

            if ($blur.val().length < 3) {
                $blur.addClass('warning');
            }

            if (type === 'email' && !_this.email($blur.val())) {
                $blur.addClass('warning');
            }
        });

        $form.on('submit', function (e) {
            var valid = true;

            $input.each(function () {
                $this = $(this);
                if ($this.hasClass('warning') || $this.val().length < 1) {
                    $this.addClass('warning');
                    valid = false;
                }
            });

            if (!valid) {
                e.preventDefault();
                $feedback.html('Please fill out all form fields and resubmit.').removeClass('hidden').addClass('show');
            }
        });
    }

};
\$\endgroup\$
  • 1
    \$\begingroup\$ $input holds all inputs shoud be plural, what this thoes with radio buttons ($blur.val().length < 3) \$\endgroup\$ – cske Apr 24 '15 at 18:37
  • \$\begingroup\$ I would not rely on your email regex. Emails are complicated, and I suggest this Stack Overflow post for more help. \$\endgroup\$ – Alex L Jan 2 '16 at 23:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.