If the basic validations are not enough you can extend the Ketchup Plugin with ease. Lets see how to do it.
Lets create a validation that take no arguments and simply checks the for the word 'tomato'.
<form action="validation.html" id="example3">
<div>
<label for="ex3_tomato">Tomatos only</label>
<input type="text" id="ex3_tomato" class="validate(tomato)" />
</div>
<div class="submit">
<input type="submit" value="Ketchup it!" />
</div>
</form>
First we need to set the error message that gets displayed in case validation do not pass. Either extend the file jquery.ketchup.messages.js or set your own messages in your own script file:
$.fn.ketchup.messages = {
'tomato': 'I only like tomato!'
}
Next we extend Ketchup with our validation function that simply checks for the word 'tomato'. Validation functions must return true or false. The first two arguments in the validation function must be the field element and the value. You can use these objects in your validation like so:
$.fn.ketchup.validation('tomato', function(element, value) {
if(value == 'tomato') return true;
else return false;
});
Now just activate Ketchup like you normally would do. We use the default settings in this example:
$(document).ready(function() {
$('#example3').ketchup();
});
Sometimes you need to validate two or more fields with the same function but with different informations. Ketchup's validation function can take as many arguments as you want. In this example we validate that the value is one of two words.
<form action="validation.html" id="example4">
<div>
<label for="ex4_yesno">Yes or No</label>
<input type="text" id="ex3_yesno" class="validate(either(yes,no))" />
</div>
<div>
<label for="ex4_km">Ketchup or Mustard</label>
<input type="text" id="ex3_km" class="validate(either(ketchup,mustard))" />
</div>
<div class="submit">
<input type="submit" value="Ketchup it!" />
</div>
</form>
You can format the output message with place holders for the arguments ($arg1, $arg2, $arg3...) you passing into your validation function. In our example the two words we want to check for:
$.fn.ketchup.messages = {
'either': 'Must be either $arg1 or $arg2.'
}
Now to the interesting part. You remember that the first two arguments for a validation function must be field and value? Every argument after these belongs to you, or better, to your validation function you set in your markup. We want to check for two words, two arguments:
$.fn.ketchup.validation('either', function(element, value, word1, word2) {
var valueL = value.toLowerCase();
if(valueL == word1.toLowerCase() || valueL == word2.toLowerCase()) return true;
else return false;
});
Activate Ketchup on the form and voilĂ :
$(document).ready(function() {
$('#example4').ketchup();
});