hello
I'm trying to add the area code to phone numbers. I used an inherited method where the phone numbers should be formatted, but when I add a number to the phone field, my code doesn't work as expected.
I have an issue where, when I add a number to the field and press enter or click elsewhere, the format according to my code should be +52 1 xx xxxx xxxx. However, for some numbers, it doesn't respect this format and appears as +52 xx xxxx xxxx, and in some cases as +52 xxx xxx xxxx.
Here is my code:
def format_phone(self, phone_number):
clean_number = re.sub(r'\D', '', phone_number) # Remove all non-numeric characters
if if len(clean_number) == 10: # If it's a 10-digit number
return '+52 1 ' + clean_number[:2] + ' ' + clean_number[2:6] + ' ' + clean_number[6:] else: return phone_number # Return the number unchanged if it doesn't have 10 digits
@api.onchange('phone') def _onchange_phone(self):
if self.phone:
phone_pattern = re.compile(r'^\+52\s1\s\d{2}\s\d{4}\s\d{4}$') # Expected format
clean_number = re.sub(r'\D', '', self.phone)
if not phone_pattern.match(self.phone) and len(clean_number) == 10:
self.phone = self.format_phone(self.phone)
_logger.info("Formatted phone number: %s", self.phone)
@api.onchange('mobile')
def _onchange_mobile(self):
if self.mobile:
phone_pattern = re.compile(r'^\+52\s1\s\d{2}\s\d{4}\s\d{4}$') # Expected format
clean_number = re.sub(r'\D', '', self.mobile)
if not phone_pattern.match(self.mobile) and len(clean_number) == 10:
self.mobile = self.format_phone(self.mobile)
_logger.info("Formatted mobile number: %s", self.mobile)