jQuery is still very useful and jQuery validate is great for validation. I’ve written before about how to make custom validators for it . Here are four more (all in coffeescript) that I’ve found quite handy:
(Greater | Less) than or equal to another element
The [data-other-element]
is supposed to be set to the name of another element in the form.
$ . validator . addMethod 'gte' , (( value , element ) ->
$otherElement = $ ( element ). parents ( "form" ). find ( "[name*='" + $ ( element ). data ( "other-element" ) + "']" )
parseInt ( value , 10 ) >= parseInt ( $otherElement . val (), 10 )
), 'It must be greater than or equal to the other element.'
$ . validator . addMethod 'lte' , (( value , element ) ->
$otherElement = $ ( element ). parents ( ".row" ). find ( "[name*='" + $ ( element ). data ( "other-element" ) + "']" )
parseInt ( value , 10 ) <= parseInt ( $otherElement . val (), 10 )
), 'It must be less than or equal to the other element.'
Strict minimum
Explicitly greater than and not empty.
$ . validator . addMethod 'minStrict' , (( value , el , param ) ->
value > param || value == ""
)
Complete URL
I’m not entire sure where I got the regular expression from though, I didn’t make that. The link to the source that I did have is broken now.
jQuery . validator . addMethod 'complete_url' , ( val , elem ) ->
if val . length == 0
return true
if ! /^(https?|ftp):\/\//i . test ( val )
val = 'http://' + val
$ ( elem ). val val
/^(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i . test val
Conditional required
Required based on the value of another field. In this case it just for a string.
$ . validator . addMethod 'required_if' , (( value , el , param ) ->
$other_element = $ ( "#" + $ ( el ). data ( "element" ))
$value = $ ( el ). data ( "value" )
if $other_element . val () == $value
return value != ""
else
return true
), "This field is required."