Programmatically: How to create custom Magento validators
Step 1: Create a new PHP file in your module's Validator directory
Create a new file named MyCustomValidator.php in your module's app/code/local/YourCompany/YourModule/Validator directory.
Step 2: Define the validator class
In MyCustomValidator.php, define the class that extends Mage_Core_Model_Validator_Abstract:
class YourCompany_YourModule_Model_Validator_CustomValidator extends Mage_Core_Model_Validator_Abstract
{
public function isValid($value)
{
// Your validation logic goes here
// For example, let's say you want to validate a string
if (strlen($value) < 5) {
return false;
}
return true;
}
public function getError()
{
return 'The value must be at least 5 characters long.';
}
}
Step 3: Register the validator
In your module's config.xml file, add the following code to register the validator:
<global>
<models>
<validators>
<customvalidator>
<class>yourcompany_yourmodule_model_validator_customvalidator</class>
</customvalidator>
</validators>
</models>
</global>
Step 4: Use the validator
To use your custom validator, you can inject it into a form or a grid. For example, if you're creating a custom form, you can use it like this:
$form = Mage::app()->getForm('your_form');
$form->addField('my_field', 'text', array(
'required' => true,
'validate' => array('customvalidator')
));