Dynamic Advanced Form Validation Plugin - jQuery Form Validator

Dynamic Advanced Form Validation Plugin - jQuery Form Validator
File Size: 9.04 KB
Views Total:
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

A dynamic, flexible, advanced jQuery form validator plugin for web developers who prefer to have full control over the validation rules (Regex), error messages, custom filters and more.

How to use it:

1. To get started, include the JavaScript library after jQuery.

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" 
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" 
        crossorigin="anonymous">
</script>
<script src="form-validator.js"></script>

2. Add span elements next to the input fields that will be used to display error messages when the input fiels are invalid. The novalidate attribute is used to disable the native HTML5 form validation functionality.

<form novalidate id="myform">
  <input id="username" type="text">
  <span id="name-error"></span>
  <label>E-mail:</label>
  <input id="email" type="email" class="form-control">
  <span id="email-error"></span>
  ... more input fields here
  <input type="submit" value="Submit">
</form>

3. Apply your own validation rules to the input fields using the following parameters:

const formsToValidate = [{
  formId: "myform",
  inputs: [{
    inputId: "username",
    alertId: "name-error",
    minLength: 3,
    maxLength: 21,
    blockSpace: true,
    required: true,
    lengthMessage: 'Name must be between %min and %max characters!', //Custom lengthMessage.
    blockSpaceMessage: "Spaces are not allowed.",
    listener: function (valid, errors, regexStatus) {
      $('#name-error').css('background-color', valid ? '#85e085' : '#ffb3b3');
    }
  },{
    inputId: "email",
    alertId: "email-error",
    minLength: 5,
    maxLength: 100,
    blockSpace: true,
    required: true,
    customFilter: function (input) {
      filteredErrors = [];
      if (input.toLowerCase() == '[email protected]')
        filteredErrors.push('EMAIL_ALREADY_USED');
      return filteredErrors;
    },
    listener: function (valid, errors, regexStatus) {
      if (!valid && errors.includes('EMAIL_ALREADY_USED'))
        $('#email').text('This e-mail has already used! Please, insert another address.');
    },
    regexMessage: 'Please enter a valid e-mail!',
    validatedMessage: "Valid e-mail!"
  }]
}];

4. Enable the validation rules you specify.

prepareFormsToValidate(formsToValidate);

5. Validate the form on submit.

function validate(formElement) { 
  return validateForm(getFormInfo(formElement.getAttribute('id'), null));
}
<form novalidate id="myform" onsubmit="return validate(this);">
  ...
</form>

This awesome jQuery plugin is developed by RodDevelopment. For more Advanced Usages, please check the demo page or visit the official website.