Opened 19 years ago

Closed 18 years ago

Last modified 17 years ago

#264 closed enhancement (fixed)

None

Reported by: hugo <gb@…> Owned by: Adrian Holovaty
Component: Contrib apps Version: unicode
Severity: normal Keywords: None
Cc: None Triage Stage: Ready for checkin
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

IP addresses are quite custom values so I think creating a validator for that type would be justified. Here is my take at the problem:

import re

IP = re.compile('^\d+\.\d+\.\d+\.\d+$')
def isIPAddress(field_data, all_data):
    if IP.match(field_data):
        parts = [0 <= int(el) <= 255 for el in field_data.split('.')]
        if len(parts) == 4: return
    raise validators.ValidationError("Please enter a dotted number notation for an IP address")

Change History (6)

comment:1 by hugo <gb@…>, 19 years ago

Summary: add a validator for IP addressesadd a validator for IPv4 addresses

As pointed out, this is only an IPv4 address validator.

comment:2 by hugo <gb@…>, 19 years ago

Summary: add a validator for IPv4 addressesPatch: add a validator for IPv4 addresses

comment:3 by Simon Willison, 19 years ago

There is a bug in your code: it will flag "99.99.99.99" as valid - parts will be [False, False, False, False] but the length of that list is still 4. The fix is to do this:

parts = [el for el in field_data.split('.') if 0 <= int(el) <= 255]

I would suggest renaming "parts" to "valid_parts" to make the code more clear - also, "IP" should be "ip_re" for consistency with the other validators. Here's an updated version of the validator:

import re

ip_re = re.compile('^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')

def isIPAddress(field_data, all_data):
    if ip_re.match(field_data):
        valid_parts = [el for el in field_data.split('.') if 0 <= int(el) <= 255]
        if len(valid_parts) == 4:
            return True
        raise validators.ValidationError("Please enter a dotted number notation for an IP address")

comment:4 by Adrian Holovaty, 19 years ago

Component: Core frameworkValidators

comment:5 by Adrian Holovaty, 18 years ago

Resolution: fixed
Status: newclosed

Fixed in [671].

comment:6 by anonymous, 17 years ago

Cc: None added
Component: ValidatorsContrib apps
Keywords: None added
Summary: Patch: add a validator for IPv4 addressesNone
Triage Stage: AcceptedReady for checkin
Version: unicode
Note: See TracTickets for help on using tickets.
Back to Top