Note: This blog is targeted for Joomla! Developers
Doing validation on client side, before form is submitted to server is always recommended. If you have developed a Joomla! extension you might have used some of the validators that Joomla! provides, which are listed below. Joomla! provides these basic form validators which you can use in your Joomla! form, although, there can be situations where the form fields you are using need different validations than what Joomla! validators offer. In this blog we will see how to add custom validators in Joomla!.
required
validate-username
validate-password
validate-numeric
validate-email
validate-[custom]
In this blog we will see how we can add validate-[custom].
If you want a custom handler, you can add one to the class, as in the following example. Make sure that the validate.js & jQuery has been loaded before this.
Also, Add a behavior to your form view template, JHTML::_('behavior.formvalidator');
jQuery(document).ready(function(){ document.formvalidator.setHandler('date', function(value) { regex=/^\d{4}-\d{2}-\d{2}$/; return regex.test(value); }); });
You can then add validate-date class to any field to make it validate as yyyy-mm-dd.
Here are few more custom validators which you will required to validate your form instead of writing javascript for each field.
document.formvalidator.setHandler('whole-number', function(value, element) { value = punycode.toASCII(value); var regex = /^[0-9]{1,9}$/; return regex.test(value); });
This will validate all the whole numbers.
Example:
document.formvalidator.setHandler('natural-number', function(value, element) { value = punycode.toASCII(value); var regex = /^[1-9]\d*$/; return regex.test(value); });
This will validate all the natural numbers.
Example:
document.formvalidator.setHandler('ymd-number', function(value, element) { var regex = /^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/; return regex.test(value); });
This will validate the field in YYYY/MM/DD format
Example:
document.formvalidator.setHandler('datetime', function(value, element) { var regex = /^(\d{4})(\/|\-)(\d{1,2})(\/|\-)(\d{1,2})\s(\d{1,2})(\/|\:)(\d{1,2})(\/|\:)(\d{1,2})$/; return regex.test(value); });
This will validate the field in YYYY/MM/DD H:I:S
Example:
That's for Custom Validators. Hope this blog was helpful for you. :)
When you subscribe to the blog, we will send you an e-mail when there are new updates on the site so you wouldn't miss them.