Ognjen Regoje bio photo

MY NAME IS
Ognjen Regoje
BUT YOU CAN CALL ME OGGY


I make things that run on the web (mostly).

More /ABOUT me.

And about /PROJECTS I've been involved in.

Email me at me@ognjen.io

me@ognjen.io Twitter LinkedIn Instagram Github

How to make custom validators for jQuery validate

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

#jquery #jquery validate #technical