Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate form input fields using jquery

  1. I'm working on form validation. Everything is working fine what I actually want is I want to add some more input fields like checkbox, radio button, select and textarea, upload file and like so into the form I want them to be validated as well.

  2. I got the email input error working but it is not working correctly as it should validate the email first and then it should remove the error message but it is removing the error message just after entering few characters.

  3. I want the phone number to be validated. Like the user should enter 10 numeric digits that is in India if in another country that will differ I am a bit confused how to do it.

  4. I want a success message to pop up when all the fields are correctly validated as they should. what I tried is this:

    $('.success_msg').fadeIn().delay(3000).fadeOut();
    $('input , textarea , select').val('').removeClass('valid');
    event.preventDefault();
    
  5. I want all the fields to be cleared when all the validations are done and the success message is sent.

Can anyone point me in the right direction?

var Validator = function(formObject) {
  this.form = $(formObject);

  var Elements = {
    name: {
      reg: /^[a-zA-Z]{2,20}$/,
      error: "Not a valid name.",
    },

    email: {
      reg: /^[a-z-0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i,
      error: "Not a valid e-mail address.",
    },
    phone: {
      reg: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
      error: "Not a valid number.",
    },

    message: {
      reg: /^(?!\s*$).+/,
      error: "Message field cannot be empty.",
    },
  };

  var handleError = function(element, message) {
    element.addClass('input-error');
    var $err_msg = element.parent('div');
    $err_msg.find('.error').remove();
    var error = $('<div class="error"></div>').text(message);
    error.appendTo($err_msg);
    element.keyup(function() {
      $(error).fadeOut(1000, function() {
        element.removeClass('input-error');
      });
    });

  };

  this.validate = function() {
    var errorCount = 0;
    this.form.find("input, textarea").each(function(index, field) {
      var type = $(field).data("validation");
      var validation = Elements[type];
      if (validation) {
        if (!validation.reg.test($(field).val())) {
          errorCount++;
          handleError($(field), validation.error);
        }
      }
    })
    return errorCount == 0;
  };
};

$(function() {
  $("form#test").on("submit", function(event) {
    //event.preventDefault();
    return new Validator(this).validate(); // "this" here refers to the form

  })
})
body {
  background: #fff;
  color: #333;
  font: 76% Verdana, sans-serif;
}

form {
  margin: 1em 0 0 2em;
  width: 90%;
}

fieldset {
  margin: 0;
  border: 1px solid #ccc;
  padding-bottom: 1em;
}

legend {
  font-weight: bold;
  text-transform: uppercase;
}

label {
  float: left;
  width: 5em;
  padding-right: 2em;
  font-weight: bold;
}

div {
  margin-bottom: 30px;
}

input {
  font: 1em Verdana, sans-serif;
}

fieldset ul li input {
  float: left;
  width: 120px;
  border: 1px solid #ccc;
}

textarea {
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
  font: 1em Verdana, sans-serif;
}

form p {
  margin: 0;
  padding: 0.4em 0 0 7em;
}

form p input {
  background: #666;
  color: #fff;
  font-weight: bold;
}

div.error {
  clear: left;
  margin-left: 5.3em;
  color: red;
  padding-right: 1.3em;
  height: 100%;
  padding-bottom: 0.3em;
  line-height: 1.3;
}

.input-error {
  background: #ff9;
  border: 1px solid red;
}

.success_msg {
  width: 350px;
  line-height: 40px;
  border: 1px solid green;
  border-radius: 5px;
  background-color: rgba(213, 255, 187, 0.7);
  display: none;
  position: absolute;
  bottom: 5px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 999;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="test">

  <fieldset>

    <legend>Contact information</legend>


    <div>
      <label for="firstname">Firstname:</label>
      <input type="text" name="firstname" id="firstname" data-validation="name" />
    </div>


    <div>
      <label for="lastname">Lastname:</label>
      <input type="text" name="lastname" id="lastname" data-validation="name" />
    </div>

    <div>
      <label for="email">Email:</label>
      <input type="email" name="email" id="email" data-validation="email" />

    </div>
    <div>
      <label for="phone">phone</label>
      <input type="number" name="phone" id="phone" data-validation="phone" />
    </div>

    <div>
      <label>Gender:</label>
      <input type="radio" name="gender" value="male" data-validation="gender" />
      <input type="radio" name="gender" value="female" data-validation="gender">
    </div>

    <div>
      <label>select</label>
      <input type="checkbox" name="checkbox" id="checkbox1" value="demo1" data-validation="checkbox" />
      <input type="checkbox" name="checkbox" id="checkbox2" value="demo2" data-validation="checkbox" />
      <input type="checkbox" name="checkbox" id="checkbox3" value="demo3" ata-validation="checkbox" />
    </div>

    <select data-validation="selectOption">
      <option value="">Select any option</option>
      <option value="red">Red</option>
      <option value="blue">Blue</option>
      <option value="green">Green</option>
    </select>

    <div>
      <label>Upload:</label>
      <input type="file" name="file" id="file" data-validation="file" />
    </div>

    <div>
      <label for="message">Message:</label>
      <textarea id="message" name="message" cols="30" rows="15" data-validation="message"></textarea>
    </div>

    <p><input type="submit" name="send" id="send" value="Send" /></p>

  </fieldset>
  <div class="success_msg">
    <p>Form submitted Successfully</p>
  </div>
</form>

Please feel free to clear your doubts before you invest your time answering the question.

like image 292
Mohammed Wahed Khan Avatar asked May 31 '18 11:05

Mohammed Wahed Khan


People also ask

How we can validate a form using jQuery?

jQuery(document). ready(function() { jQuery("#forms). validate({ rules: { firstname: 'required', lastname: 'required', u_email: { required: true, email: true,//add an email rule that will ensure the value entered is valid email id. maxlength: 255, }, } }); });

Does jQuery validate require a form?

The jquery validate plugin requires a form element to function, so you should have your form fields (no matter how few) contained inside a form. You can tell the validation plugin not to operate on form submission, then manually validate the form when the correct submit button is clicked.

How do you check if jQuery validate is working?

The plugin adds a validationPlugin function to jQuery. fn , so simply check whether it exists or not; if (typeof jQuery. fn.

What is validation in jQuery?

Form validation is a process of confirming the relevant information entered by the user in the input field. Here we will be validating a simple form that consists of a username, password and a confirmed password using jQuery.


1 Answers

Here is the working code:

https://jsfiddle.net/bhumi/o2gxgz9r/47570/

I have changed selector to use id

You need to use loop in handle error:

var Validator = function(form) {

    this.form = $(form);

    var Elements = {
        name: {
            selector: $('input[type=text]'),
            reg: /^[a-zA-Z]{2,20}$/
        },

        email: {
            selector: $('input[type=email]'),
            reg: /^[a-z-0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i
        },

        message: {
            selector: $('textarea'),
            reg: /^\s+$/
        }
    };

    var handleError = function(element, message, v1) {
        if (v1.selector.length > 1) {
            var ss = v1.selector;

            $(ss).each(function(i, v) {
            $(v).removeClass('input-error');
            if($(v).val() == ''){
              $(v).addClass('input-error');
              var $err_msg = $(v).parent('div');
              if($(v).parent('div').find('.error').length == 0) {
                    var error = $('<div class="error"></div>').text(message);
               }else{
                    $(v).parent('div').find('.error').text('');
                    var error = $(v).parent('div').find('.error').text(message);
                    $(this).siblings('.error').show();
               }
               error.appendTo($err_msg);
             }else{
               $(v).siblings('.error').text('')
             }
             $(v).keyup(function() {
                 $(error).fadeOut(1000, function() {
                     element.removeClass('input-error');
                });
             });
          });
        } else {
            element.addClass('input-error');
            var $err_msg = element.parent('div');
            if(element.parent('div').find('.error').length == 0) {
                  var error = $('<div class="error"></div>').text(message);
             }else{
                  element.parent('div').find('.error').text('');
                  var error = element.parent('div').find('.error').text(message);
                  $(this).siblings('.error').show();
             }
            error.appendTo($err_msg);
            element.keyup(function() {
                $(error).fadeOut(1000, function() {
                    element.removeClass('input-error');
                });
            });
        }

    };

    this.validate = function() {

        this.form.submit(function(e) {

            for (var i in Elements) {

                var type = i;
                var validation = Elements[i];
                switch (type) {
                    case 'name':
                        if (!validation.reg.test(validation.selector.val())) {
                            handleError(validation.selector, 'Not a valid name.', validation);
                        }
                        break;
                    case 'email':
                        if (!validation.reg.test(validation.selector.val())) {
                            handleError(validation.selector, 'Not a valid e-mail address.', validation);
                        }
                        break;
                    case 'message':
                        if (validation.reg.test(validation.selector.val()) || validation.selector.val() == '') {
                        handleError(validation.selector, 'Message field cannot be empty.', validation);
                        }
                        break;
                    default:
                        break;


                }

            }

            e.preventDefault();
        });

    };
};

var validator = new Validator('#test');
validator.validate();
like image 52
Bhumi Shah Avatar answered Oct 16 '22 05:10

Bhumi Shah