~kkubasik/django/aggregation-branch

« back to all changes in this revision

Viewing changes to django/core/validators.py

  • Committer: adrian
  • Date: 2006-05-02 01:31:56 UTC
  • Revision ID: vcs-imports@canonical.com-20060502013156-2941fcd40d080649
MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards-incompatible. Please read http://code.djangoproject.com/wiki/RemovingTheMagic for upgrade instructions.

Show diffs side-by-side

added added

removed removed

Lines of Context:
8
8
form field is required.
9
9
"""
10
10
 
 
11
from django.conf import settings
 
12
from django.utils.translation import gettext, gettext_lazy, ngettext
 
13
from django.utils.functional import Promise, lazy
11
14
import re
12
15
 
13
16
_datere = r'(19|2\d)\d{2}-((?:0?[1-9])|(?:1[0-2]))-((?:0?[1-9])|(?:[12][0-9])|(?:3[0-1]))'
24
27
slug_re = re.compile(r'^[-\w]+$')
25
28
url_re = re.compile(r'^https?://\S+$')
26
29
 
27
 
from django.conf.settings import JING_PATH
28
 
from django.utils.translation import gettext_lazy, ngettext
29
 
from django.utils.functional import Promise, lazy
30
 
 
31
30
lazy_inter = lazy(lambda a,b: str(a) % b, str)
32
31
 
33
32
class ValidationError(Exception):
58
57
 
59
58
def isAlphaNumeric(field_data, all_data):
60
59
    if not alnum_re.search(field_data):
61
 
        raise ValidationError, _("This value must contain only letters, numbers and underscores.")
 
60
        raise ValidationError, gettext("This value must contain only letters, numbers and underscores.")
62
61
 
63
62
def isAlphaNumericURL(field_data, all_data):
64
63
    if not alnumurl_re.search(field_data):
65
 
        raise ValidationError, _("This value must contain only letters, numbers, underscores, dashes or slashes.")
 
64
        raise ValidationError, gettext("This value must contain only letters, numbers, underscores, dashes or slashes.")
66
65
 
67
66
def isSlug(field_data, all_data):
68
67
    if not slug_re.search(field_data):
70
69
 
71
70
def isLowerCase(field_data, all_data):
72
71
    if field_data.lower() != field_data:
73
 
        raise ValidationError, _("Uppercase letters are not allowed here.")
 
72
        raise ValidationError, gettext("Uppercase letters are not allowed here.")
74
73
 
75
74
def isUpperCase(field_data, all_data):
76
75
    if field_data.upper() != field_data:
77
 
        raise ValidationError, _("Lowercase letters are not allowed here.")
 
76
        raise ValidationError, gettext("Lowercase letters are not allowed here.")
78
77
 
79
78
def isCommaSeparatedIntegerList(field_data, all_data):
80
79
    for supposed_int in field_data.split(','):
81
80
        try:
82
81
            int(supposed_int)
83
82
        except ValueError:
84
 
            raise ValidationError, _("Enter only digits separated by commas.")
 
83
            raise ValidationError, gettext("Enter only digits separated by commas.")
85
84
 
86
85
def isCommaSeparatedEmailList(field_data, all_data):
87
86
    """
93
92
        try:
94
93
            isValidEmail(supposed_email.strip(), '')
95
94
        except ValidationError:
96
 
            raise ValidationError, _("Enter valid e-mail addresses separated by commas.")
 
95
            raise ValidationError, gettext("Enter valid e-mail addresses separated by commas.")
97
96
 
98
97
def isValidIPAddress4(field_data, all_data):
99
98
    if not ip4_re.search(field_data):
100
 
        raise ValidationError, _("Please enter a valid IP address.")
 
99
        raise ValidationError, gettext("Please enter a valid IP address.")
101
100
 
102
101
def isNotEmpty(field_data, all_data):
103
102
    if field_data.strip() == '':
104
 
        raise ValidationError, _("Empty values are not allowed here.")
 
103
        raise ValidationError, gettext("Empty values are not allowed here.")
105
104
 
106
105
def isOnlyDigits(field_data, all_data):
107
106
    if not field_data.isdigit():
108
 
        raise ValidationError, _("Non-numeric characters aren't allowed here.")
 
107
        raise ValidationError, gettext("Non-numeric characters aren't allowed here.")
109
108
 
110
109
def isNotOnlyDigits(field_data, all_data):
111
110
    if field_data.isdigit():
112
 
        raise ValidationError, _("This value can't be comprised solely of digits.")
 
111
        raise ValidationError, gettext("This value can't be comprised solely of digits.")
113
112
 
114
113
def isInteger(field_data, all_data):
115
114
    # This differs from isOnlyDigits because this accepts the negative sign
116
115
    if not integer_re.search(field_data):
117
 
        raise ValidationError, _("Enter a whole number.")
 
116
        raise ValidationError, gettext("Enter a whole number.")
118
117
 
119
118
def isOnlyLetters(field_data, all_data):
120
119
    if not field_data.isalpha():
121
 
        raise ValidationError, _("Only alphabetical characters are allowed here.")
 
120
        raise ValidationError, gettext("Only alphabetical characters are allowed here.")
122
121
 
123
122
def isValidANSIDate(field_data, all_data):
124
123
    if not ansi_date_re.search(field_data):
125
 
        raise ValidationError, _('Enter a valid date in YYYY-MM-DD format.')
 
124
        raise ValidationError, gettext('Enter a valid date in YYYY-MM-DD format.')
126
125
 
127
126
def isValidANSITime(field_data, all_data):
128
127
    if not ansi_time_re.search(field_data):
129
 
        raise ValidationError, _('Enter a valid time in HH:MM format.')
 
128
        raise ValidationError, gettext('Enter a valid time in HH:MM format.')
130
129
 
131
130
def isValidANSIDatetime(field_data, all_data):
132
131
    if not ansi_datetime_re.search(field_data):
133
 
        raise ValidationError, _('Enter a valid date/time in YYYY-MM-DD HH:MM format.')
 
132
        raise ValidationError, gettext('Enter a valid date/time in YYYY-MM-DD HH:MM format.')
134
133
 
135
134
def isValidEmail(field_data, all_data):
136
135
    if not email_re.search(field_data):
137
 
        raise ValidationError, _('Enter a valid e-mail address.')
 
136
        raise ValidationError, gettext('Enter a valid e-mail address.')
138
137
 
139
138
def isValidImage(field_data, all_data):
140
139
    """
146
145
    try:
147
146
        Image.open(StringIO(field_data['content']))
148
147
    except IOError: # Python Imaging Library doesn't recognize it as an image
149
 
        raise ValidationError, _("Upload a valid image. The file you uploaded was either not an image or a corrupted image.")
 
148
        raise ValidationError, gettext("Upload a valid image. The file you uploaded was either not an image or a corrupted image.")
150
149
 
151
150
def isValidImageURL(field_data, all_data):
152
151
    uc = URLMimeTypeCheck(('image/jpeg', 'image/gif', 'image/png'))
153
152
    try:
154
153
        uc(field_data, all_data)
155
154
    except URLMimeTypeCheck.InvalidContentType:
156
 
        raise ValidationError, _("The URL %s does not point to a valid image.") % field_data
 
155
        raise ValidationError, gettext("The URL %s does not point to a valid image.") % field_data
157
156
 
158
157
def isValidPhone(field_data, all_data):
159
158
    if not phone_re.search(field_data):
160
 
        raise ValidationError, _('Phone numbers must be in XXX-XXX-XXXX format. "%s" is invalid.') % field_data
 
159
        raise ValidationError, gettext('Phone numbers must be in XXX-XXX-XXXX format. "%s" is invalid.') % field_data
161
160
 
162
161
def isValidQuicktimeVideoURL(field_data, all_data):
163
162
    "Checks that the given URL is a video that can be played by QuickTime (qt, mpeg)"
165
164
    try:
166
165
        uc(field_data, all_data)
167
166
    except URLMimeTypeCheck.InvalidContentType:
168
 
        raise ValidationError, _("The URL %s does not point to a valid QuickTime video.") % field_data
 
167
        raise ValidationError, gettext("The URL %s does not point to a valid QuickTime video.") % field_data
169
168
 
170
169
def isValidURL(field_data, all_data):
171
170
    if not url_re.search(field_data):
172
 
        raise ValidationError, _("A valid URL is required.")
 
171
        raise ValidationError, gettext("A valid URL is required.")
173
172
 
174
173
def isValidHTML(field_data, all_data):
175
174
    import urllib, urllib2
183
182
        return
184
183
    from xml.dom.minidom import parseString
185
184
    error_messages = [e.firstChild.wholeText for e in parseString(u.read()).getElementsByTagName('messages')[0].getElementsByTagName('msg')]
186
 
    raise ValidationError, _("Valid HTML is required. Specific errors are:\n%s") % "\n".join(error_messages)
 
185
    raise ValidationError, gettext("Valid HTML is required. Specific errors are:\n%s") % "\n".join(error_messages)
187
186
 
188
187
def isWellFormedXml(field_data, all_data):
189
188
    from xml.dom.minidom import parseString
190
189
    try:
191
190
        parseString(field_data)
192
191
    except Exception, e: # Naked except because we're not sure what will be thrown
193
 
        raise ValidationError, _("Badly formed XML: %s") % str(e)
 
192
        raise ValidationError, gettext("Badly formed XML: %s") % str(e)
194
193
 
195
194
def isWellFormedXmlFragment(field_data, all_data):
196
195
    isWellFormedXml('<root>%s</root>' % field_data, all_data)
200
199
    try:
201
200
        u = urllib2.urlopen(field_data)
202
201
    except ValueError:
203
 
        raise ValidationError, _("Invalid URL: %s") % field_data
 
202
        raise ValidationError, gettext("Invalid URL: %s") % field_data
204
203
    except urllib2.HTTPError, e:
205
204
        # 401s are valid; they just mean authorization is required.
206
205
        if e.code not in ('401',):
207
 
            raise ValidationError, _("The URL %s is a broken link.") % field_data
 
206
            raise ValidationError, gettext("The URL %s is a broken link.") % field_data
208
207
    except: # urllib2.URLError, httplib.InvalidURL, etc.
209
 
        raise ValidationError, _("The URL %s is a broken link.") % field_data
 
208
        raise ValidationError, gettext("The URL %s is a broken link.") % field_data
210
209
 
211
210
def isValidUSState(field_data, all_data):
212
211
    "Checks that the given string is a valid two-letter U.S. state abbreviation"
213
212
    states = ['AA', 'AE', 'AK', 'AL', 'AP', 'AR', 'AS', 'AZ', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'FM', 'GA', 'GU', 'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MH', 'MI', 'MN', 'MO', 'MP', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM', 'NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'PR', 'PW', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VA', 'VI', 'VT', 'WA', 'WI', 'WV', 'WY']
214
213
    if field_data.upper() not in states:
215
 
        raise ValidationError, _("Enter a valid U.S. state abbreviation.")
 
214
        raise ValidationError, gettext("Enter a valid U.S. state abbreviation.")
216
215
 
217
216
def hasNoProfanities(field_data, all_data):
218
217
    """
334
333
        from math import log
335
334
        val = log(int(field_data)) / log(self.power_of)
336
335
        if val != int(val):
337
 
            raise ValidationError, _("This value must be a power of %s.") % self.power_of
 
336
            raise ValidationError, gettext("This value must be a power of %s.") % self.power_of
338
337
 
339
338
class IsValidFloat:
340
339
    def __init__(self, max_digits, decimal_places):
345
344
        try:
346
345
            float(data)
347
346
        except ValueError:
348
 
            raise ValidationError, _("Please enter a valid decimal number.")
 
347
            raise ValidationError, gettext("Please enter a valid decimal number.")
349
348
        if len(data) > (self.max_digits + 1):
350
 
            raise ValidationError, ngettext( "Please enter a valid decimal number with at most %s total digit.",
 
349
            raise ValidationError, ngettext("Please enter a valid decimal number with at most %s total digit.",
351
350
                "Please enter a valid decimal number with at most %s total digits.", self.max_digits) % self.max_digits
352
351
        if '.' in data and len(data.split('.')[1]) > self.decimal_places:
353
352
            raise ValidationError, ngettext("Please enter a valid decimal number with at most %s decimal place.",
424
423
        try:
425
424
            info = urllib2.urlopen(field_data).info()
426
425
        except (urllib2.HTTPError, urllib2.URLError):
427
 
            raise URLMimeTypeCheck.CouldNotRetrieve, _("Could not retrieve anything from %s.") % field_data
 
426
            raise URLMimeTypeCheck.CouldNotRetrieve, gettext("Could not retrieve anything from %s.") % field_data
428
427
        content_type = info['content-type']
429
428
        if content_type not in self.mime_type_list:
430
 
            raise URLMimeTypeCheck.InvalidContentType, _("The URL %(url)s returned the invalid Content-Type header '%(contenttype)s'.") % {
 
429
            raise URLMimeTypeCheck.InvalidContentType, gettext("The URL %(url)s returned the invalid Content-Type header '%(contenttype)s'.") % {
431
430
                'url': field_data, 'contenttype': content_type}
432
431
 
433
432
class RelaxNGCompact:
447
446
        fp = open(filename, 'w')
448
447
        fp.write(field_data)
449
448
        fp.close()
450
 
        if not os.path.exists(JING_PATH):
451
 
            raise Exception, "%s not found!" % JING_PATH
452
 
        p = os.popen('%s -c %s %s' % (JING_PATH, self.schema_path, filename))
 
449
        if not os.path.exists(settings.JING_PATH):
 
450
            raise Exception, "%s not found!" % settings.JING_PATH
 
451
        p = os.popen('%s -c %s %s' % (settings.JING_PATH, self.schema_path, filename))
453
452
        errors = [line.strip() for line in p.readlines()]
454
453
        p.close()
455
454
        os.unlink(filename)