Magento custom form validation

Share

Custom validation method

Adding a new validation rule into a form in Magento is easy as adding a “required” class for a input form. While existing validation rules can be seen in fileĀ js/prototype/prototype.js there is an easy way to add your own validation rule.

Add following inline JavaScript into template or load it in separate file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<script type="text/javascript">
//<![CDATA[
Validation.add('required-classname','<?php echo __('Please enter valid value.'); ?>',function(value){
if(value == null)
{
return false;
}
/*
* Your code here
* Return true if you like the value
*/
});
//]]>
</script>

First parameter is the classname for your input element. The second parameter is the error message for invalid input. Third parameter is a function where your code lies. The function should return false on invalid value.

Calling existing validation methods

Yes, that’s easy! It’s very useful to be able to access existing validations for example when checking sub part of a value. In this example

1
2
3
if (Validation.get('validate-email').test("example@examplecom") == false) {
// Not a valid email
}

You can see complete list of existing validation methods in fileĀ js/prototype/prototype.js.

Comments are closed.