0

I added one field of mobile number in customer/account/create form. I want to put validation in mobile field which allow 10 digit mobile number format . If mobile number format is not valid then display error message as per email id validation.

As per mention in image i want to display error message for mobile number validation.

How to apply client side validation for mobile number?

Please help me...

Thanks in advance :)

enter image description here

1

In Magento the validation is done through validation.js

lib/web/mage/validation.js

In this file you will find a number of validation functions.

Now lets see how you can apply validation to your field. Lets take an example of postcode field. If you look at the code in checkout_index_index.xml you will see there is a node called validation. You can add multiple validation this way like I have added alphanumeric.

 <item name="postcode" xsi:type="array">
        <item name="component" xsi:type="string">Magento_Ui/js/form/element/post-code</item>
        <item name="validation" xsi:type="array">
            <item name="required-entry" xsi:type="string">true</item>
            <item name="alphanumeric" xsi:type="string">true</item>
        </item>
    </item>
</item>

Function is defined in validation.js like this.

"alphanumeric": [
            function (value, element) {
                return this.optional(element) || /^\w+$/i.test(value);
            },
            'Letters, numbers, spaces or underscores only please'
        ],

Hope this helps!

UPDATE: Add your custom function in this file:

app/code/[Vendor]/[ThemName]/Magento_Ui/web/js/lib/validation/rules.js

like this

mobilelimitdigit": [
        function(value) {
            return value.length > 9 &&  value.length < 11 
            && value.match(/^\d{10}$/);
        },
        $.mage.__('Please specify a valid 10 digits mobile number')
    ],
  • 1
    Please read question. I want to mobile number validation. 10 digit number can enter only...Letters and Underscores not allow in this field. – Rohan Hapani May 19 '17 at 9:10
  • Yes off course. That was just an example of how you can add validation for a field. For mobile number you can add your own function or use the one from the available functions. – Sejal Shah May 19 '17 at 9:14
  • see my updated answer. – Sejal Shah May 19 '17 at 9:19
  • You can also use "validate-length maximum-length-10 minimum-length-10" – Sejal Shah May 19 '17 at 9:25
  • 1
    "validate-length maximum-length-10 minimum-length-10" this class is not working :( . can i override rules.js in my custom module? – Rohan Hapani May 19 '17 at 9:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.