Magento, thanks to Prototype framework, has nice set of JavaScript validators - so we can validate user input without reloading site. Of course, we cannot rely only on it, but it is good starting point - and for majority of users, it will have good look'n'feel.
But sometimes bulit-in validators are just not enough - for example, we can add custom fields for customer account, address etc. and we need some custom validation there. Magento together with Prototype gives us quick and easy way.
Little bit of theory - Prototype gives us Validation class. To check if form is valid, we have to call validate() method, which checks validation classes. I say classes, cause those are defined by css classes for input, for example:
will require to be not-empty. It would be nice to add our own classes to keep this process so simple as it is. So...
Step 1.
Create your own file, for example /skin/frontend/default/your_skin/js/myvalidation.js and add it to page.xml layout file.
Important note: it must be somewhere below adding script prototype/validation.js - usually, end of head block is good and safe place.
Step 2.
Editing myvalidation.js. Take a look on following code:
Validation.addAllThese([ // 2.
[
'validation-myown', // 3.
'Please insert proper word', // 4.
function(v,r){return v.indexOf('valid')==-1?false:true} // 5.
],
[] // 6.
])
}
Little explanations.
- We don't want to make any JavaScript error if for some reason validation script is not enabled, so we ensure it exists
- Adding a validators. Argument is array, each value of it is also array - so you can add multiple validators at once.
- This is css class that validator will be searching for, note that it must begin with validation- ('-' sign at end) - otherwise it may not work as desired.
- This is error message displayed when validation is not passed.
- Finally, our most important function - validator itself.
- Next validators...
In this example validator function takes two arguments, but in fact usually first one is enough.
So first - called v here - is value of input at moment of validation
Second - called r here - can be useful in very custom validators - it is reference to validated object.
When validator function returns true, validation for field is passed, if false - opposite.
That's it. Quite simple if you will understand process ;)
Step 3. (optional)
We have nice error message - but what about case we need to translate it? Well, we can use Magento JavaScript class - Translate. Adding translations is quite simple, but has to be done from template level. We can use Jakub's module (blog.baobaz.com/en/blog/magento-translations-module):
Translator.add('Please insert proper word','<?php echo Mage::helper('translations')->__('Please insert proper word')?>');
</script>
Add this to template where you use your custom validators or create special block for it, so they can be easily reused.
Anything more on validators is just plain JavaScript and your needs :)