This question has been flagged
1 Reply
9755 Views

Hello guys, please help me to do validation in my custom module.

i want to develop a HR module with Employee name, date of birth and age. in my module i want validate age should above 18 years and do not exceed 120 years.

please let me know, how to improve my code here is my code.

in my .py file

from osv import fields, osv
from datetime import datetime
from time import strptime
from dateutil import parser

class employee_employee(osv.osv):

    _name='employee.employee'

#   Age calculation

    def onchange_age(self, cr, uid, ids, DOB, context=None):
        current_date=datetime.now()
        current_year=current_date.year
        birth_date = parser.parse(DOB)

        if birth_date.year > current_year-120 and birth_date.year<current_year-18:
            current_age=current_year-birth_date.year
        else:
            raise osv.except_osv(_('Invalid DOB'), _('Please enter a valid DATE OF BIRTH'))

        val = {
        'age':current_age
        }
        return {'value': val}

    _columns ={ 
          'name':fields.char('Emp Name',size=64, required=True),
          'DOB':fields.date('DOB'),
                  'age':fields.char('Age'),
        }

employee_employee()

in my .xml

   <record id="employee_form_view" model="ir.ui.view">
        <field name="name">employee.employee.form</field>
        <field name="model">employee.employee</field>
        <field name="type">form</field>
        <field name="arch" type="xml">

           <form string="employee">
            <field name="name"/>
                    <field name="DOB" />
                    <field name="age"/>
            </form>
        </field>
    </record>

Thanks in advance....

Avatar
Discard
Best Answer

Hi,

Replace <field name="DOB"/> with <field name="DOB" on_change="onchange_age(DOB)"/> to call onchange method.

You can apply constraint for the specific field which will check the age based on birth date. And it will not allow you to save record. For an example, you may have a look @ here.

Avatar
Discard
Author

i know, on_change event is good, but it doesn't make professional project. bcz when we enter a dob before 120 years like (01/01/1891), it shows validation error, after i click ok the dob field still same, and it could be saved without a restriction, that is my problem.

Author

i know, on_change event is good, but it doesn't make professional project. bcz when we enter a dob before 120 years like (01/01/1891), it shows validation error, after i click ok the dob field still same, and it could be saved without a restriction, that is my problem.

I have edited my answer, just have a look.

Author

Very thanks Nehal