Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #264 -- Added django.core.validators.isValidIPAddress4. Thanks,…

… Hugo and Simon

git-svn-id: http://code.djangoproject.com/svn/django/trunk@671 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 3d426607a8e04f79fb4ee4393e92c4838539bd23 1 parent 36fc73a
Adrian Holovaty authored September 23, 2005
11  django/core/formfields.py
@@ -687,6 +687,17 @@ def isValidURL(self, field_data, all_data):
687 687
             raise validators.CriticalValidationError, e.messages
688 688
 
689 689
 class IPAddressField(TextField):
  690
+    def __init__(self, field_name, length=15, maxlength=15, is_required=False, validator_list=[]):
  691
+        validator_list = [self.isValidIPAddress] + validator_list
  692
+        TextField.__init__(self, field_name, length=length, maxlength=maxlength,
  693
+            is_required=is_required, validator_list=validator_list)
  694
+
  695
+    def isValidIPAddress(self, field_data, all_data):
  696
+        try:
  697
+            validators.isValidIPAddress4(field_data, all_data)
  698
+        except validators.ValidationError, e:
  699
+            raise validators.CriticalValidationError, e.messages
  700
+
690 701
     def html2python(data):
691 702
         return data or None
692 703
     html2python = staticmethod(html2python)
8  django/core/validators.py
@@ -19,6 +19,7 @@
19 19
 ansi_datetime_re = re.compile('^%s %s$' % (_datere, _timere))
20 20
 email_re = re.compile(r'^[-\w.+]+@\w[\w.-]+$')
21 21
 integer_re = re.compile(r'^-?\d+$')
  22
+ip4_re = re.compile(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')
22 23
 phone_re = re.compile(r'^[A-PR-Y0-9]{3}-[A-PR-Y0-9]{3}-[A-PR-Y0-9]{4}$', re.IGNORECASE)
23 24
 url_re = re.compile(r'^http://\S+$')
24 25
 
@@ -85,6 +86,13 @@ def isCommaSeparatedEmailList(field_data, all_data):
85 86
         except ValidationError:
86 87
             raise ValidationError, "Enter valid e-mail addresses separated by commas."
87 88
 
  89
+def isValidIPAddress4(field_data, all_data):
  90
+    if ip4_re.search(field_data):
  91
+        valid_parts = [el for el in field_data.split('.') if 0 <= int(el) <= 255]
  92
+        if len(valid_parts) == 4:
  93
+            return
  94
+    raise validators.ValidationError, "Please enter a valid IP address."
  95
+
88 96
 def isNotEmpty(field_data, all_data):
89 97
     if field_data.strip() == '':
90 98
         raise ValidationError, "Empty values are not allowed here."

0 notes on commit 3d42660

Please sign in to comment.
Something went wrong with that request. Please try again.