Skip to Content
Menu
This question has been flagged
1 Reply
230 Views



<xpath expr="//field[@name='phone']" position="attributes">

<attribute name="placeholder">05XXXXXXXX</attribute>

<attribute name="required">1</attribute>

<attribute name="maxlength">10</attribute>

</xpath>

Avatar
Discard
Best Answer

Hi,

To prevent the user from entering more than 10 digits in a phone number field in Odoo, especially from the XML view side, your current approach will not work in standard Odoo for Char fields because Odoo does not natively pass maxlength from XML to the HTML input.


*  Add size=10 to the field definition in Python

       In your model (res.partner or custom model), define:

            phone = fields.Char(string="Phone", size=10)

                   -This limits stored data to 10 characters at the database level.

                   - But it won’t prevent a user from entering more than 10 until saving.


* Backend validation with @api.constrains

            @api.constrains('phone')

             def _check_phone_length(self):

                         for rec in self:

                                phone = (rec.phone or '').strip()

                                digits_only = re.sub(r'\D', '', phone)

                                 if len(digits_only) != 10:

                                         raise ValidationError(_("Phone number must contain exactly 10 digits."))

This guarantees data integrity even if a frontend check is bypassed.


Hope it helps

Avatar
Discard
Related Posts Replies Views Activity
0
Jul 25
105
1
Jul 25
386
0
Jul 25
359
1
Jun 25
417
1
Jun 25
401