Django MultiWidget Phone Number Field

后端 未结 4 649
执笔经年
执笔经年 2020-12-31 20:54

I want to create a field for phone number input that has 2 text fields (size 3, 3, and 4 respectively) with the common \"(\" \")\" \"-\" delimiters. Below is my code for th

4条回答
  •  长发绾君心
    2020-12-31 21:16

    I took hughdbrown's advise and modified USPhoneNumberField to do what I need. The reason I didn't use it initially was that it stores phone numbers as XXX-XXX-XXXX in the DB, I store them as XXXXXXXXXX. So I over-rode the clean method:

    class PhoneNumberField(USPhoneNumberField):
        def clean(self, value):
            super(USPhoneNumberField, self).clean(value)
            if value in EMPTY_VALUES:
                return u''
            value = re.sub('(\(|\)|\s+)', '', smart_unicode(value))
            m = phone_digits_re.search(value)
            if m:
                return u'%s%s%s' % (m.group(1), m.group(2), m.group(3))
            raise ValidationError(self.error_messages['invalid'])
    

提交回复
热议问题