Programmatically: How to use Magento's custom validation mechanism for custom form validation
Step 1: Create a custom validation class
Create a new PHP file, e.g., MyCompany/MyModule/Model/Form/Validator/MyValidation.php:
class MyCompany_MyModule_Model_Form_Validator_MyValidation
extends Mage_Core_Model_Form_Validator_Abstract
{
public function validate($object)
{
// Your custom validation logic goes here
// For example, let's say we want to validate a password field
$password = $object->getData('password');
if (strlen($password) < 8) {
$this->_addError('Password must be at least 8 characters');
}
return $this->_getMessages();
}
}
Step 2: Register the validation class in your module's config file
Add the following code to your module's etc/config.xml file:
<?xml version="1.0"?>
<config>
<!-- ... -->
<global>
<models>
<mycompany_mymodule>
<class>MyCompany_MyModule_Model</class>
</mycompany_mymodule>
</models>
<forms>
<myform_validator>
<class>MyCompany_MyModule_Model_Form_Validator_MyValidation</class>
</myform_validator>
</forms>
</global>
<!-- ... -->
</config>
Step 3: Use the custom validation class in your form
Modify your form's XML file (e.g., app/design/frontend/yourtheme/template/form.phtml) to include the custom validation class:
<?xml version="1.0"?>
<form xmlns="urn:magento:frontend:en_us">
<!-- ... -->
<field name="password" validate="myform_validator">
<!-- ... -->
</field>
<!-- ... -->
</form>
Step 4: Test your custom validation
Submit your form with a password that is too short (e.g., less than 8 characters). You should see an error message indicating that the password is too short.