Opened 10 years ago

Closed 9 years ago

Last modified 8 years ago

#264 closed enhancement (fixed)

None

Reported by: hugo <gb@…> Owned by: adrian
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: UI/UX:

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 Changed 10 years ago by hugo <gb@…>

  • Summary changed from add a validator for IP addresses to add a validator for IPv4 addresses

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

comment:2 Changed 10 years ago by hugo <gb@…>

  • Summary changed from add a validator for IPv4 addresses to Patch: add a validator for IPv4 addresses

comment:3 Changed 10 years ago by Simon Willison

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 Changed 10 years ago by adrian

  • Component changed from Core framework to Validators

comment:5 Changed 9 years ago by adrian

  • Resolution set to fixed
  • Status changed from new to closed

Fixed in [671].

comment:6 Changed 8 years ago by anonymous

  • Cc None added
  • Component changed from Validators to Contrib apps
  • Keywords None added
  • Summary changed from Patch: add a validator for IPv4 addresses to None
  • Triage Stage changed from Accepted to Ready for checkin
  • Version set to unicode
Note: See TracTickets for help on using tickets.
Back to Top