Phone Number Validation

65 views
Skip to first unread message

Carl Brubaker

unread,
Mar 15, 2018, 11:17:49 PM3/15/18
to Django users
I'm trying to make my own phone number form, and I'm having trouble with number validation.

Since international numbers can use "(40) (30)" I want to check that only numbers were entered. I can't seem to make it work though.

def clean_international(self):
        data = self.cleaned_data['international']
        # Take off ()
        dataless = data.strip('() ')
         
        if dataless.isdigit() != True:
            raise ValidationError(_('Invalid number'))
       
        return data

This always raises an error. Any suggestions? Thanks!

Bernd Wechner

unread,
Mar 15, 2018, 11:57:54 PM3/15/18
to Django users
Not really a Django question, just basic Python.

For starters strip() will remove only leading and trailing chars in the set, not embedded chars.

Curiously though, with all due respect, this:

 if dataless.isdigit() != True:

has beginner written all over it. What's wrong with:

 if not dataless.isdigit():

Comparing booleans by value is an interesting notion.

But personally, Django is rooted on the principle of DRY (Don't Repeat Yourself) and if I wanted to store phone numbers I'd look to see who's done it already and lo and behold django-phonenumber-field!

https://github.com/stefanfoulis/django-phonenumber-field

Try that maybe and save yourself a lot of thinking and hassle on the phone number formats.

Regards,

Bernd.

Carl Brubaker

unread,
Mar 16, 2018, 6:48:08 AM3/16/18
to Django users
Guilty as charged! Now that you mention "not", I remember seeing that in a tutorial.

As for doing it again, I hate my job and don't have time or resources to quit and go to school, so I'm trying to learn on the fly. I hope to write a program to do my current job, because, so far, the ones I've used are terrible. I am currently doing some things the hard way (like defining my own views when I could use generic) so I can understand how they work when I get to more complex things. And hopefully after a few years I can "try to take over the world" (-Brain, if anyone remembers). If that doesn't work out, hopefully I can build a portfolio to show to an employer that might hire me.

Thanks!
Reply all
Reply to author
Forward
0 new messages