With the help of Matthéo Geoffray
, this is what I did to apply frontend validation for custom attributes.
[
'type' => 'int',
'backend' => '',
'frontend' => '',
'label' => 'XXXX',
'input' => 'text',
'frontend_class' => 'validate-greater-than-zero',
'source' => '',
'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
'visible' => true,
'required' => true,
'user_defined' => false,
'default' => 0,
'searchable' => false,
'filterable' => true,
'comparable' => false,
'visible_on_front' => false,
'used_in_product_listing' => true,
'unique' => false
]
This is the custom attribute in install script.
I added plugin in di.xml
<type name="Magento\Catalog\Ui\DataProvider\CatalogEavValidationRules">
<plugin name="namespace_custom_validation_for_product_attribute" type="Namespace\Module\Model\Plugin\Product\ValidationRules"/>
</type>
Here is the plugin code.
<?php
namespace Namespace\Module\Model\Plugin\Product;
use Closure;
class ValidationRules
{
/**
* @param \Magento\Catalog\Ui\DataProvider\CatalogEavValidationRules $rulesObject
* @param callable $proceed
* @param \Magento\Catalog\Api\Data\ProductAttributeInterface $attribute,
* @param array $data
* @return array
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function aroundBuild(
\Magento\Catalog\Ui\DataProvider\CatalogEavValidationRules $rulesObject,
Closure $proceed,
\Magento\Catalog\Api\Data\ProductAttributeInterface $attribute,
array $data
){
$rules = $proceed($attribute,$data);
if($attribute->getAttributeCode() == 'xyz'){ //custom filter
$validationClasses = explode(' ', $attribute->getFrontendClass());
foreach ($validationClasses as $class) {
$rules[$class] = true;
}
}
return $rules;
}
}
Basically in \Magento\Catalog\Ui\DataProvider\CatalogEavValidationRules
, the method called mapRules
only matches the frontend class against limited number of validation rules. To apply more validation rules we need to append rules using plugin.
For server side validation, Please refer to Matthéo Geoffray
answer.