Magento – Magento 2: Custom validation on product attribute

attributesmagento-2.1magento2product-attributevalidation

There are only six validation available for product attributes

  1. validate-number (Decimal Number)
  2. validate-digits (Integer Number)
  3. validate-email (Email)
  4. validate-url (URL)
  5. validate-alpha (Letters)
  6. validate-alphanum (Letters (a-z, A-Z) or Numbers (0-9))

I follow this link and add new(Value Greater than 0) validation to product attribute with the upgradeData script.

But it uses backend class for validate attribute value and validate value at the time of saving attribute. But I want JS validation which should working on tab key.

Have anyone an idea about custom JS validation on product attribute?

Best Answer

You have to write js validation functions like validate-email and other functions you mentioned. You can write your custom funtion in rules.js by overriding it in this way:

Vendor file :

vendor\magento\module-ui\view\base\web\js\lib\validation\rules.js

Override file in custom theme :

app/design/frontend/Package/themename/Magento_Ui/web/js/lib/validation/rules.js

There is already a function for value greater than 0:

validate-greater-than-zero