Husna
Husna

Reputation: 1386

Validate all input fields all at once based on required attribute

I've been working on a form with multiple fields like text, number and textarea.

What I want is:

I want to validate the form with input type having required attribute all in one condition for example if we select input type as text then all text field should be validated together like name, message, teaxtarea and all the related text fields (if any). and in the same condition, I want other input fields like number, radio, checkbox, select and file to be validated.

I have my custom forms working perfectly fine, but that is based on Id's. I want it to be based on input type with required attribute(as mentioned above). What actually is the problem with my forms is if I have it on Id's based and when I have like two to three forms on the same page that is getting conflicted.

Here is the working Fiddle followed by the code.

$(document).ready(function() {
  var Validator = function(form) {

    this.form = $(form);

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

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

      phone: {
        selector: $('#phone'),
        reg: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/
      },

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

    var handleError = function(element, message) {
      element.addClass('input-error');
      var $li = element.parent('<div>');
      var error = $('<div class="error"></div>').text(message);
      error.appendTo($li);
      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.');
              }
              break;
            case 'email':
              if (!validation.reg.test(validation.selector.val())) {
                handleError(validation.selector, 'Not a valid e-mail address.');
              }
              break;
            case 'string':
              if (validation.reg.test(validation.selector.val()) || validation.selector.val() == '') {
                handleError(validation.selector, 'Special characters now allowed or empty element.');
              }
              break;
            case 'empty':
              if (validation.reg.test(validation.selector.val()) || validation.selector.val() == '') {
                handleError(validation.selector, 'Message field cannot be empty.');
              }
              break;
            default:
              break;


          }

        }

        e.preventDefault();
      });

    };
  };

  var validator = new Validator('#test');
  validator.validate();

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="test" method="post" action="">

  <div id="note"></div>

  <div class="detail">
    <input type="text" id="name" name="name" autocomplete="off" required />
    <label for="name">Name</label>
  </div>
  <!--detail-->
  <div class="detail">
    <input type="text" id="email" name="email" autocomplete="off" required />
    <label for="email">Email</label>
  </div>
  <!--detail-->
  <div class="detail">
    <input type="number" id="phone" autocomplete="off" name="phone" required />
    <label for="phone">Phone Number</label>
  </div>
  <!--detail-->
  <div class="detail">
    <input type="text" id="enquiry" autocomplete="off" name="enquiry" required />
    <label for="enquiry">I want to know about...</label>
  </div>
  <!--detail-->
  <div class="detail message">
    <textarea type="text" id="message" autocomplete="off" name="message" required></textarea>
    <label for="message">Type your Message here</label>
  </div>
  <!--detail-->

  <!-- <div class="detail">
   <input type="radio" id="contact_male" name="gender" value="male" required />
							<input type="radio" id="contact_female" name="gender" value="female" required />
						</div>
  <detail-->


  <!-- <div class="detail">
  <input type="checkbox" id="contact_html" name="html" required />HTMl
							<input type="checkbox" id="contact_css" name="css" required />CSS
						</div>
  <detail-->


  <div class="btn-container" id="submit">
    <button type="submit">Submit</button>
  </div>

</form>

Upvotes: 0

Views: 4147

Answers (1)

Shahrukh Ahmad
Shahrukh Ahmad

Reputation: 163

Here's what I do when dealing with so many input fields , get all the input elements through jquery , and apply your work (i.e validation) in loop , something like this:

var items = $(parentElement).find("input,select");
for (var i = 0; i < items.length; i++)
            {
                var validator = new Validator(items[i]);
                validator.validate();
            }

Upvotes: 0

Related Questions