jQuery.isValid

jQuery.isValid is a form validation plugin that includes multiple types of error checking, customisation of error messages and how/when they are shown.

Get Started

To use jQuery.isValid, make sure you have jQuery and then add the following markup to your html:

                
<!-- Styles -->
<link type="text/css" href="css/jQuery.isValid.css" rel="stylesheet" />

<!-- Scripts Unminified -->
<script type="text/javascript" src="/js/moment.js"></script>
<script type="text/javascript" src="/js/checkPostCode.js"></script>
<script type="text/javascript" src="/js/jQuery.isValid.js"></script>

<!-- Scripts Minified -->
<script type="text/javascript" src="/js/moment.js"></script>
<script type="text/javascript" src="/js/jQuery.isValid.min.js"></script>
                
            

They can be found in the dist folder in the repository, both minified and unminified.

There is a dependency on moment.js and the checkPostCode is a function just split out into a single file. Credit to John Gardner for this.

How it works

To validate the fields in your form using the plugin, add an attribute to the input/select/checkbox element that you need to validate called data-field-type and pass in the field option that the field represents. The html below shows how this is implemented. A more complicated implementation are shown in the examples section.

                    
<form id="simple-form">
    <div class="form-row">
        <label for="general">General Field</label>
        <input type="text"
               data-field-type="general"
               name="general" />
    </div>
    <div class="form-row">
        <label for="emailAddress">Email</label>
        <input type="text"
               data-field-type="email"
               name="emailAddress" />
    </div>
    <div class="form-row">
        <label>&nbsp;</label>
        <input type="submit" value="Submit" class="form-btn" />
    </div>
</form>
                    
                

You can see in the markup that the 2 inputs both have attributes of data-field-type. The first is the general option and the second is email. This is used in the plugin to know what validation methods to run against your field.

To then initialise the plugin, use the normal jQuery selector and then .isValid() as demonstrated in the javascript below. This will create an instance using all the defaults. Options may be customised through passed options into the plugin, using the html and adding more attributes or a combination of the two.

                    
 $(document).ready(function() {
    $('#simple-form').isValid();
});
                    
                

Examples

Below you will find a variety of examples, varying from simple to complicated as well as using both javacript and html to pass options in.

                
<form id="simple-form">
    <div class="form-row">
        <label for="general">General Field</label>
        <input type="text"
               data-field-type="general"
               name="general" />
    </div>
    <div class="form-row">
        <label for="emailAddress">Email</label>
        <input type="text"
               data-field-type="email"
               name="emailAddress" />
    </div>
    <div class="form-row">
        <label>&nbsp;</label>
        <input type="submit" value="Submit" class="form-btn" />
    </div>
</form>

$(document).ready(function() {
    $('#simple-form').isValid();
});
                
            
                
<form id="complex-form" class="isValid">
    <div class="form-row">
        <label for="username">Username</label>
        <input type="text"
               data-field-type="general"
               data-error-message="Please enter a Username"
               placeholder="Enter Username"
               name="username" />
    </div>
    <div class="form-row">
        <label for="subject">Subject</label>
        <select id="subject" name="subject" data-field-type="select">
            <option disabled selected>Choose Subject</option>
            <option value="Question">Question</option>
            <option value="Feedback">Feedback</option>
            <option value="Mentor">Want to be a Mentor</option>
        </select>
    </div>
    <div class="form-row">
        <label for="role">Role</label>
        <select id="role"
                name="role"
                data-field-type="select"
                data-required-error-message="Choosing a role is mandatory" >
            <option disabled selected>Choose Role</option>
            <option value="Junior">Junior</option>
            <option value="Mid">Mid</option>
            <option value="Senior">Senior</option>
        </select>
    </div>
    <div class="form-row">
        <label for="email">Email</label>
        <input type="text"
               data-field-type="email"
               placeholder="Enter email"
               name="email" />
    </div>
    <div class="form-row">
        <label for="emailConfirm">Email</label>
        <input type="text"
               data-field-type="emailConfirm"
               placeholder="Confirm Email"
               name="emailConfirm" />
    </div>
    <div class="form-row">
        <label for="password">Password</label>
        <input type="password"
               data-field-type="password"
               data-format-error-message="Password is weak brah. Mix it up."
               placeholder="Enter Password"
               name="password" />
    </div>
    <div class="form-row">
        <label for="passwordConfirm">Confirm</label>
        <input type="password"
               data-field-type="passwordConfirm"
               placeholder="Confirm Password"
               name="passwordConfirm" />
    </div>
    <div class="form-row">
        <label for="date">Date</label>
        <input type="text"
               id="datepicker"
               data-field-type="date"
               data-allowed-date-error-message="Date is in the future. Not allowed."
               placeholder="DD/MM/YYYY"
               name="date" />
    </div>
    <div class="form-row">
        <label for="postcode">Post Code</label>
        <input type="text"
               data-field-type="postCode"
               data-invalid-error-message="Postcode is made up. Try again."
               placeholder="Enter PostCode"
               name="postCode" />
    </div>
    <div class="form-row">
        <label for="numbers">Number</label>
        <input type="text"
               data-field-type="numbers"
               data-invalid-error-message="Do they look like numbers to you?"
               placeholder="Enter number"
               name="numbers" />
    </div>
    <div class="form-row">
        <label for="terms">Terms</label>
        <input type="checkbox"
               data-field-type="checkbox"
               data-required-error-message="Tick it fool. Tick it."
               name="terms" />
    </div>
    <div class="form-row">
        <label>&nbsp;</label>
        <input type="submit" value="Submit" class="form-btn" />
    </div>
</form>

$('#complex-form').isValid({
    password: {
        numbers: true,
        passwordConfirm: true
    },
    email: {
        emailConfirm: true
    },
    emailConfirm: {
        invalidErrorMessage: 'Do not match'
    },
    date: {
        allowFutureDates: false,
        invalidErrorMessage: 'Invalid Date entered'
    }
});
                
            

Validators

jQuery.isValid has the option for you to create your own custom fieldType and validator. The plugin offers a bunch of default options, however you may have a specific fieldType like an ID Number or a Username which have a specific requirement for it to be valid. You can create your own validator and then the plugin will use that validator and run it just like the default built in validators.

So long as your validator matches the structure shown and returns the expected object type everything will work like it's part of the plugin! Example of an ID number are shown below:

                    
var validatorForm = $('#validator-form').isValid({
      fieldTypes: {
          idNumber: {
              requiredErrorMessage: 'Please specify your ID Number',
              formatErrorMessage: 'ID Number is incorrect format',
              callbacks: {
                  onValidated: function(event) {
                      console.log(event);
                  }
              }
          }
      },
      validators: {
          idNumber: {
              name: 'isIDNumberValid',
              validate: function(field) {

                  var validResult = field.val().length === 6 && /^[0-9]+$/.test(field.val()),
                      errorType = validResult ? '' : 'format';

                  return {
                      isValid: validResult,
                      activeErrorType: errorType
                  };
              }
          }
      }
  }).data('isValid');
                    
                

Options

The majority of the options in the plugin are various different types of field that each consist of their own validators. However there are also some other core options for further control over each aspect of the plugin.

The properties shown in the table below exist for every field option:

activeErrorMessage The currently active error message being displayed
requiredErrorMessage The currently active error message being displayed
callbacks onValidated and onInvalidated each trigger dependent on fields valid state

Field Options

The plugin field options refer to the various types of data the plugin is expecting and can therefore validate.

  • general
  • letters
  • numbers
  • decimals
  • password
  • passwordConfirm
  • email
  • emailConfirm
  • date
  • postCode
  • select
  • checkbox

The breakdown of those options and their properties:

general

Type: Object

Use general if field is required and doesn't do or need any sort of other validation.

activeErrorMessage - string

Currently active error message

requiredErrorMessage - string

'Field is required'

callbacks - object

onValidated - function(event) {}
onInvalidated - function(event) {}

letters

Type: Object

Use letters if field is required and the field should only be made up of letters.

activeErrorMessage - string

Currently active error message

requiredErrorMessage - string

'Field is required'

invalidErrorMessage - string

'Field is letters only'

callbacks - object

onValidated - function(event) {}
onInvalidated - function(event) {}

numbers

Type: Object

Use numbers if field is required and the field should only be made up of numbers.

activeErrorMessage - string

Currently active error message

requiredErrorMessage - string

'Field is required'

invalidErrorMessage - string

'Field is numbers only'

callbacks - object

onValidated - function(event) {}
onInvalidated - function(event) {}

decimals

Type: Object

Use decimals if field is required and the field should only be made up of decimals.

activeErrorMessage - string

Currently active error message

requiredErrorMessage - string

'Field is required'

invalidErrorMessage - string

'Field is decimals only'

callbacks - object

onValidated - function(event) {}
onInvalidated - function(event) {}

password

Type: Object

Use password if field is required and the field is a password field.

activeErrorMessage - string

Currently active error message

requiredErrorMessage - string

'Password is required'

invalidErrorMessage - string

'Password should be more than 6 characters'

formatErrorMessage - string

'Password should contain numbers and letters'

minLength - number

6

maxLength - number

100

numbers - boolean

false

letters - boolean

true

passwordConfirm - boolean

false (set to true if passwordConfirm field exists)

callbacks - object

onValidated - function(event) {}
onInvalidated - function(event) {}

passwordConfirm

Type: Object

Use passwordConfirm if field is required and the form already contains a password field.

activeErrorMessage - string

Currently active error message

requiredErrorMessage - string

'Confirming your Password is required'

invalidErrorMessage - string

'Passwords do not match'

callbacks - object

onValidated - function(event) {}
onInvalidated - function(event) {}

email

Type: Object

Use email if field is required and the field is an email field.

activeErrorMessage - string

Currently active error message

requiredErrorMessage - string

'Email is required'

invalidErrorMessage - string

'Please enter a valid email address'

domainErrorMessage - string

'Email domain should be @xxxx.com'

domain - string

'' e.g. @gmail.com

emailConfirm - boolean

false (set to true if emailConfirm field exists)

callbacks - object

onValidated - function(event) {}
onInvalidated - function(event) {}

emailConfirm

Type: Object

Use emailConfirm if field is required and the form already contains an email field.

activeErrorMessage - string

Currently active error message

requiredErrorMessage - string

'Confirming your Email is required'

invalidErrorMessage - string

'Email addresses do not match'

callbacks - object

onValidated - function(event) {}
onInvalidated - function(event) {}

date

Type: Object

Use date if field is required and the field needs to be in a date format.

activeErrorMessage - string

Currently active error message

requiredErrorMessage - string

'Date is required'

invalidErrorMessage - string

'Please enter a valid Date'

formatErrorMessage - string

'Date format doesn\'t match DD/MM/YYYY'

allowedDateErrorMessage - string

'Date not allowed'

format - string

'DD/MM/YYY'

allowFutureDates - boolean

true

callbacks - object

onValidated - function(event) {}
onInvalidated - function(event) {}

postCode

Type: Object

Use postCode if field is required and the field needs to be a valid Postcode.

activeErrorMessage - string

Currently active error message

requiredErrorMessage - string

'Post Code is required'

invalidErrorMessage - string

'Please enter a valid Post Code'

callbacks - object

onValidated - function(event) {}
onInvalidated - function(event) {}

select

Type: Object

Use select if field is required and you are using a select form element.

activeErrorMessage - string

Currently active error message

requiredErrorMessage - string

'Choosing an option is required'

callbacks - object

onValidated - function(event) {}
onInvalidated - function(event) {}

checkbox

Type: Object

Use checkbox if field is required and you are using a checkbox form element.

activeErrorMessage - string

Currently active error message

requiredErrorMessage - string

'Checkbox is required'

callbacks - object

onValidated - function(event) {}
onInvalidated - function(event) {}

Other Options

The remaining options are global controls for the whole plugin rather than the individual fields.

validateOnBlur

Type: boolean

Controls whether fields should be validated when they tabbed/clicked out of.

validateOnBlur - boolean

true

enableErrorMessages

Type: boolean

Global control to show or hide all error message for each field type.

enableErrorMessages - boolean

true

submitButton

Type: boolean

The submit button that should validate and submit the form. Initially null and uses the submit button found in the form if not specified.

submitButton - null

null (uses default form submit unless specified)

errorTypes

Type: object

An object containing the various errorTypes that are used in the plugin and the value associated with each type. Custom ones can be created.

errorTypes - {}

Default error types:
required, invalid, format, domain, allowedDate

validators

Type: object

An object containing the fieldTypes that can be validated by the plugin. Includes all the default ones and the names of the methods it runs. Custom ones can be created, specifying the fieldType and then within that, the name and the validator method.

validators - {}

Defaults include all fieldTypes, e.g.
general: { name: 'isGeneralValid' }

onFormValidated

Type: function

Controls whether fields should be validated when they tabbed/clicked out of.

onFormValidated - function

function() {}

onFormInvalidated

Type: function

A callback that can be used when the form as a whole is invalidated.

onFormInvalidated - function

function() {}

Browser Support

Tested in:

It could well work in other browsers, but I just haven't tested in every single one.

Improvements

If you are interested in improving the plugin in anyway, please either create or a pull request or email me aj.summerfield93@gmail.com