Skip to Content
Menu
This question has been flagged
5 Replies
10611 Views

Hello all,

I have a integer field 'is_mobile'. Where user entering mobile. I want that when user enter wrong mobile no. format then it show warning message "invalid no. format" and also form not save without right format. For this i applied code, but it is not work as per requirement. 

Code is below:

is_mobile = fields.Integer("Mobile")


@api.multi

    @api.constrains('is_mobile')

    def _check_phone_number(self):

        for rec in self:

            if rec.is_mobile and len(rec.is_mobile) != "^[0-9]{10}$" :

                raise ValidationError(_("Wrong value enter"))

            else:

                return False

        return {}


Thanks in advance

Avatar
Discard
Best Answer

Hello Pawan,
Specific about your python condition :  

if rec.is_mobile and len(rec.is_mobile) != "^[0-9]{10}$" :
I Could not understand why you need to compare regex string with length, as it going to directly compare the string only not regex output.
So, rather you can directly do something like this :
if rec.is_mobile and len(str(rec.is_mobile)) != 10 :
Avatar
Discard
Author

Hii @Parth, Your code upto 10 digits work well, But after 10 digits it shows error "The following fields are invalid: " also warning message change into error when using character and other type words. I want that warning show else than 10 digits in any condition.

Thanks for help.

Hi Pawan, The Error warning 'The following fields are invalid: ' is due to you are using is_mobile as an Integer field and it can store max 10 digits, more than that it will show error. To, avoid this you can take Char field insted.

Just sake of information :

If you are about to develope something in odoo you can even use the default phone validation module provided by odoo. Where you have to just define phone widget in xml view.

<field name="phone" widget="phone"/>

And make sure module 'phone_validation' will install. This module will validate the phone number according to the country selected.

Author

Thanks parth, Now error message problem solved, but there is still one problem is that it take 10 values they might be integer, character, comma and etc. But i want only 10 integer values else validation. So, how i solve this problem for only integer 10 numbers?

Hello Pawan, For that you can make use of your regex like this,

import re

pattern = re.compile("^[0-9]{10}$")

if pattern.match(string):

return true

else:

return false

Author

Thanks parth work with following code:

@api.multi

@api.constrains('whats_app')

def _onchange_phone_number(self):

pattern = re.compile("^[0-9]{10}$")

for rec in self:

if pattern.match(rec.whats_app) and len(str(rec.whats_app)) == 10:

return True

else:

raise ValidationError(_("Invalid Mobile No."))

Related Posts Replies Views Activity
0
Sep 17
2805
3
Oct 17
20501
1
Oct 17
9882
0
Dec 24
43
2
Oct 24
217