Mingg Lex
Mingg Lex

Reputation: 151

Add validation in models in Odoo

I have a model student with the following fields.

class Student(models.Model):
    _name = "student"
    name = fields.Char(string='Name', required=True)
    nid = fields.Char(string='NID', required=True)

I need to ensure that name contains only within 10-15 alphabets and spaces and that nid starts with a capital letter, followed by 12 numbers and ends with a capital letter. Can this be done directly in the model?

Upvotes: 3

Views: 2520

Answers (1)

Charif DZ
Charif DZ

Reputation: 14721

Yes you can add this constrains using the decorator @api.constrains('field1', 'field2') witch will tell Odoo to trigger this method if one of the field (in the list of fields passed) is changed.

and using regular expression (re) module will save a lot of typing in this case.

    import re  # for matching

    class Student(models.Model):
        _name = "student"

        name = fields.Char(string='Name', required=True)

        nid = fields.Char(string='NID', required=True)

        @api.constrains('name')
        def check_name(self):
            """ make sure name 10-15 alphabets and spaces"""
            for rec in self:
                # here i forced that the name should start with alphabets if it's not the case remove ^[a-zA-Z]
                # and just keep:  re.match(r"[ a-zA-Z]+", rec.name)
                if not 10 <= len(rec.name) <= 15 or not re.match(r"^[a-zA-Z][ a-zA-Z]*", rec.name):
                    raise exceptions.ValidationError(_('your message about 10-15 alphabets and spaces'))

        @api.constrains('nid')
        def check_nid(self):
            """ make sure nid starts with capital letter, followed by 12 numbers and ends with a capital letter"""
            for rec in self:
                if not re.match(r"^[A-Z][0-9]{12}[A-Z]$", rec.nid):
                    raise exceptions.ValidationError(_('your message about capital letter, followed'
                                                       'by 12 numbers and ends with a capital letter')

Upvotes: 4

Related Questions