Adminhtml Form Field custom validation function via Prototype Js

Step 1. In your Form element add custom validate class

 
<?php
 
class Vendorname_Modulename_Block_Adminhtml_Modulename_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
 
    protected function _prepareForm()
    {
	...
        $fieldset->addField('custom_id', 'text', array(
            'label'     => Mage::helper('modulename')->__('Custom ID'),
            'class'     => 'validate-custom-id',
            'required'  => true,
            'name'      => 'custom_id'
        ));
	...

Step 2: Add the following to your extension’s app/code/local/Vendorname/Modulename/Block/Adminhtml/Modulename/Edit.php form block Edit file.
Magento uses Prototype library for validation.

 
<?php
 
class Vendorname_Modulename_Block_Adminhtml_Modulename_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
    public function __construct()
    {
        $this->_objectId = 'id';
        $this->_blockGroup = 'modulename';
        $this->_controller = 'adminhtml_modulename';
        $this->_mode = 'edit';
 
        parent::__construct();
 
        $this->_formInitScripts[] = '
            //<![CDATA[
            Validation.add(\'validate-custom-id\', \'Custom ID not selected.\', function(v) {
		return Validation.get('IsEmpty').test(v)
            })
           //]]>
           ';
    }

Step 3. In your extension, Adminhtml Form, when you click Save the field should throw a validation error if it’s empty

Leave a Reply