In the CRM module there is a mobile number field. But it is a char field I can add alphabetic characters also. I'd prefer it to work with numerals only. So I replaced mobile:fields.char('Mobile',size=20) with mobile:field.integer('Mobile'), but I can add up-to 9 digits. Is there any other way to add mobile number with integers only? We use PostgreSQL,so there is numeric as one datatype, so I also tried mobile:fields.numeric('Mobile',size=10) it is throwing me an error as:

"datatype not used in module".
有帮助吗?

解决方案

Use regular expression to validate

import re
from osv import osv,fields
class crm_lead_inherit(osv.osv):
    _name = _inherit = 'crm.lead'
    def create(self,cr,uid,vals,context=None):   
       if 'mobile' in vals and vals['mobile']:
            if re.match("^[0-9]*$", vals['mobile']) != None:
               pass
            else:
               raise osv.except_osv(_('Invalid Mobile No'),_('Please enter a valid Phone Number'))   
       return super(crm_lead_inherit, self).create(cr, uid,vals, context=context)
   def write(self,cr,uid,ids,vals,context=None):   
       if 'mobile' in vals and vals['mobile']:
            if re.match("^[0-9]*$", vals['mobile']) != None:
               pass
            else:
               raise osv.except_osv(_('Invalid Mobile No'),_('Please enter a valid Phone Number'))   
       return super(crm_lead_inherit, self).write(cr, uid,ids,vals, context=context)
crm_lead_inherit()

其他提示

senthilnathang solution is partially correct. Also it is not good to modify the create, write, search functionalities. So my opinion is to use the on_change functionality for the field mobile. In the xml view add the onchange

<field name="mobile" on_change="onchange_mobile(mobile)"/>

Then in the python file for the crm lead, inside the crmlead class,

def onchange_mobile(self, cr, uid, ids, mobile, context=None):
    if not mobile:
        return {}
    mobile = mobile.replace('.','') #removes any '.' from the string
    mobile = mobile.replace(' ','') #removes space from the string
    if not mobile.isdigit():
        raise osv.except_osv(_('Invalid Mobile No'),_('Please enter a valid Phone Number'))   
    return {}

You can remove the replace part if you want.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top