Client side validation in openerp

2019-09-10 05:43发布

I am still learning Openerp and please bear it if I asked something very simple. My issue is that I need to get validate two fields which represent start_time and end_time.

both fields are in char

'start_time': fields.char('Start Time'),
'end_time': fields.char('End Time'),

What I need to do is , once the user input this start_time and end_time I need to check if that input is in 24hrs and in hh:mm pattern.

please be kind enough to help me with this

1条回答
该账号已被封号
2楼-- · 2019-09-10 06:25

You should add an on_change function to your python code where you check if start_time and end_time is in the correct format. And in your xml you'll have to tell that the method should be called when the field changes.

XML

<field name="start_time" on_change="check_hour_format(start_time)"/>
<field name="end_time" on_change="check_hour_format(end_time)"/>

Python

the result should be something like

def check_hour_format(self,cr,uid,ids,time_field,context=None):
    if correct format  
       return {}
    else:
        warning = {'title'  : _("Warning for this value!"),
                   'message': _("Field not in correct format!"),
                  }
        return {'warning': warning}

This code should work for this issue

import time
    def check_hour_format(self,cr,uid,ids,time_field,context=None):
        try:
            time.strptime(char_input, "%H:%M")
            return {}
        except ValueError:
            warning = {'title'  : _("Warning for this value!"),
                       'message': _("Field not in correct format!"),
                      }
            return {'warning': warning}

In on_change method, you can change field value

def on_change(self, cr, uid, ids, context=None):
    # do something
    return {'value': { 'field_name': newValue},
            'warning': {'title': _("Warning"),
                        'message': _("warning message")
                       }
           }
查看更多
登录 后发表回答