Bootstrap Compatible Form Validator In jQuery - validate.js

Bootstrap Compatible Form Validator In jQuery - validate.js
File Size: 8.51 KB
Views Total: 163
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

validate.js is an easy, dynamic, extensible jQuery form validation plugin that uses Bootstrap form validation classes (or your own CSS classes) to highlight invalid form fields and display custom error messages.

How to use it:

1. Load the main script validate.js after jQuery. Note that Bootstrap framework is optional but highly recommended.

<link rel="stylesheet" href="/path/to/cdn/bootstrap.min.css" />
<script src="/path/to/cdn/jquery.slim.min.js"></script>
<script src="/path/to/cdn/bootstrap.min.js"></script>
<script src="/path/to/src/validate.js"></script>

2. Apply validation rules to your form fields and define your own error messages as follows.

var literal = {
    req1: { selector: $('#req1'), required: { message: 'Required Field.' } },
    req2: { selector: $('#req2'), digit: { message: 'Must be a digit.' } },
    req3: { selector: $('#req3'), length: { value: 3, message: 'Only 3 characters are allowed.' } },
    req4: { selector: $('#req4'), from: { value: 3, message: 'At least 3 numbers.' } },
    req5: { selector: $('#req5'), to: { value: 3, message: '3 numbers or less.' } },
    req6: { selector: $('#req6'), range: { value: [5, 10], message: 'From 5 To 10.' } },
    req7: { selector: $('#req7'), email: { message: 'Must be a valid email.' } },
    req8: { selector: $('#req8'), mobile: { message: 'Must be a valid phone number.\nEX) 01012341234' } },
    req9: { selector: $('#req9'), compare: { value: 'test', message: 'Must match the string: text.' } },
    req10: { selector: $('#req10'), date: { message: 'Must be a valid date.\nEX) 2021-01-12' } },
    req11: { selector: $('#req11'), regex: { value: /^[0-9]+$/, message: 'Custom validator using Regext.' } }
};

3. Initialize the plugin and done.

var result = $.validate.rules(literal);
console.log(result);

4. Use browser's alert function to show error messages to users.

var result = $.validate.rules(literal,{
    mode: 'alert'
});

5. Override the default CSS classes if you'd like to use other CSS frameworks.

var result = $.validate.rules(literal,{
    mode: 'bootstrap',
    bootstrap: {
      feedback: 'invalid-feedback',
      error: 'is-invalid',
      success: 'is-valid'
    }
});

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