Ognjen Regoje bio photo

Ognjen Regoje
But you can call me Oggy


I make things that run on the web (mostly).
More ABOUT me and my PROJECTS.

me@ognjen.io LinkedIn

How to make custom validators for jQuery validate

#jquery #jquery validate #technical

Occassionally you need to validate a specific rule in forms. It would be stupid to roll the entire validation library from scratch so instead it’s better to make a custom validator that works with jQuery validate. So, for example, below is a validator that checks that the user didn’t just enter all same characters.

In coffeescript:

$.validator.addMethod 'different', ((value, elem, param) ->
  counts = {}
  x = 0
  str = value
  length = value.length
  while x < length
    l = str.charAt(x)
    counts[l] = if isNaN(counts[l]) then 1 else counts[l] + 1
    x++
  if Object.keys(counts).length > 1
    return true
  else
    return false
), 'Please fill this in correctly.'

The parameters are:

  • value is the value in the input
  • elem is the input itself
  • param is the parameter passed to the validator method when you initialize the validation

Then to use it you can use it as so:

  $('form').validate
    rules:
      'user[email]':
        different: true