Magento 2 - Extend custom validation / add own validation rule
-
18-03-2021 - |
Question
In Magento 1, I used the below javascript code inside of a template to add my own validation rule:
// Add new validation class for the name. Also supports names with two hypen in the name e.g. Hans-Maier-Friedrich.
// Also supports umlauts and some special chars like é or á
Validation.add('validate-name','Please only use (A-Z a-z àèéáäÄüÜöÖ) in this field.', function(v) {
return Validation.get('IsEmpty').test(v) || /^[A-Za-zàèéáäÄüÜöÖ]+-?[A-Za-zàèéáäÄüÜöÖ]+-?[A-Za-zàèéáäÄüÜöÖ]+$/.test(v);
});
How does it work in Magento 2?
Solution
You can try something like below code, please replace validation rule and error message
<script type="text/javascript">
require([
'jquery', 'jquery/ui', 'jquery/validate', 'mage/translate', 'mage/mage'
], function($){
$.validator.addMethod(
'validate-name', function (value) {
return /^0(6|7)[0-9]{8}$/.test(value); // your validation rule here
}, $.mage.__('Your error message.'));
});
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange