Django

Code

Changeset 901

Show
Ignore:
Timestamp:
10/17/05 08:16:13 (3 years ago)
Author:
hugo
Message:

i18n: added translation hooks to all validators

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/branches/i18n/django/core/validators.py

    r726 r901  
    2525 
    2626from django.conf.settings import JING_PATH 
     27from django.utils.translation import gettext_lazy 
    2728 
    2829class ValidationError(Exception): 
     
    5859def isAlphaNumericURL(field_data, all_data): 
    5960    if not alnumurl_re.search(field_data): 
    60         raise ValidationError, "This value must contain only letters, numbers, underscores and slashes." 
     61        raise ValidationError, _("This value must contain only letters, numbers, underscores and slashes.") 
    6162 
    6263def isLowerCase(field_data, all_data): 
    6364    if field_data.lower() != field_data: 
    64         raise ValidationError, "Uppercase letters are not allowed here." 
     65        raise ValidationError, _("Uppercase letters are not allowed here.") 
    6566 
    6667def isUpperCase(field_data, all_data): 
    6768    if field_data.upper() != field_data: 
    68         raise ValidationError, "Lowercase letters are not allowed here." 
     69        raise ValidationError, _("Lowercase letters are not allowed here.") 
    6970 
    7071def isCommaSeparatedIntegerList(field_data, all_data): 
     
    7374            int(supposed_int) 
    7475        except ValueError: 
    75             raise ValidationError, "Enter only digits separated by commas." 
     76            raise ValidationError, _("Enter only digits separated by commas.") 
    7677 
    7778def isCommaSeparatedEmailList(field_data, all_data): 
     
    8586            isValidEmail(supposed_email.strip(), '') 
    8687        except ValidationError: 
    87             raise ValidationError, "Enter valid e-mail addresses separated by commas." 
     88            raise ValidationError, _("Enter valid e-mail addresses separated by commas.") 
    8889 
    8990def isValidIPAddress4(field_data, all_data): 
     
    9293        if len(valid_parts) == 4: 
    9394            return 
    94     raise validators.ValidationError, "Please enter a valid IP address." 
     95    raise validators.ValidationError, _("Please enter a valid IP address.") 
    9596 
    9697def isNotEmpty(field_data, all_data): 
    9798    if field_data.strip() == '': 
    98         raise ValidationError, "Empty values are not allowed here." 
     99        raise ValidationError, _("Empty values are not allowed here.") 
    99100 
    100101def isOnlyDigits(field_data, all_data): 
    101102    if not field_data.isdigit(): 
    102         raise ValidationError, "Non-numeric characters aren't allowed here." 
     103        raise ValidationError, _("Non-numeric characters aren't allowed here.") 
    103104 
    104105def isNotOnlyDigits(field_data, all_data): 
    105106    if field_data.isdigit(): 
    106         raise ValidationError, "This value can't be comprised solely of digits." 
     107        raise ValidationError, _("This value can't be comprised solely of digits.") 
    107108 
    108109def isInteger(field_data, all_data): 
    109110    # This differs from isOnlyDigits because this accepts the negative sign 
    110111    if not integer_re.search(field_data): 
    111         raise ValidationError, "Enter a whole number." 
     112        raise ValidationError, _("Enter a whole number.") 
    112113 
    113114def isOnlyLetters(field_data, all_data): 
    114115    if not field_data.isalpha(): 
    115         raise ValidationError, "Only alphabetical characters are allowed here." 
     116        raise ValidationError, _("Only alphabetical characters are allowed here.") 
    116117 
    117118def isValidANSIDate(field_data, all_data): 
    118119    if not ansi_date_re.search(field_data): 
    119         raise ValidationError, 'Enter a valid date in YYYY-MM-DD format.' 
     120        raise ValidationError, _('Enter a valid date in YYYY-MM-DD format.') 
    120121 
    121122def isValidANSITime(field_data, all_data): 
    122123    if not ansi_time_re.search(field_data): 
    123         raise ValidationError, 'Enter a valid time in HH:MM format.' 
     124        raise ValidationError, _('Enter a valid time in HH:MM format.') 
    124125 
    125126def isValidANSIDatetime(field_data, all_data): 
    126127    if not ansi_datetime_re.search(field_data): 
    127         raise ValidationError, 'Enter a valid date/time in YYYY-MM-DD HH:MM format.' 
     128        raise ValidationError, _('Enter a valid date/time in YYYY-MM-DD HH:MM format.') 
    128129 
    129130def isValidEmail(field_data, all_data): 
    130131    if not email_re.search(field_data): 
    131         raise ValidationError, 'Enter a valid e-mail address.' 
     132        raise ValidationError, _('Enter a valid e-mail address.') 
    132133 
    133134def isValidImage(field_data, all_data): 
     
    141142        Image.open(StringIO(field_data['content'])) 
    142143    except IOError: # Python Imaging Library doesn't recognize it as an image 
    143         raise ValidationError, "Upload a valid image. The file you uploaded was either not an image or a corrupted image." 
     144        raise ValidationError, _("Upload a valid image. The file you uploaded was either not an image or a corrupted image.") 
    144145 
    145146def isValidImageURL(field_data, all_data): 
     
    148149        uc(field_data, all_data) 
    149150    except URLMimeTypeCheck.InvalidContentType: 
    150         raise ValidationError, "The URL %s does not point to a valid image." % field_data 
     151        raise ValidationError, _("The URL %s does not point to a valid image.") % field_data 
    151152 
    152153def isValidPhone(field_data, all_data): 
    153154    if not phone_re.search(field_data): 
    154         raise ValidationError, 'Phone numbers must be in XXX-XXX-XXXX format. "%s" is invalid.' % field_data 
     155        raise ValidationError, _('Phone numbers must be in XXX-XXX-XXXX format. "%s" is invalid.') % field_data 
    155156 
    156157def isValidQuicktimeVideoURL(field_data, all_data): 
     
    160161        uc(field_data, all_data) 
    161162    except URLMimeTypeCheck.InvalidContentType: 
    162         raise ValidationError, "The URL %s does not point to a valid QuickTime video." % field_data 
     163        raise ValidationError, _("The URL %s does not point to a valid QuickTime video.") % field_data 
    163164 
    164165def isValidURL(field_data, all_data): 
    165166    if not url_re.search(field_data): 
    166         raise ValidationError, "A valid URL is required." 
     167        raise ValidationError, _("A valid URL is required.") 
    167168 
    168169def isValidHTML(field_data, all_data): 
     
    178179    from xml.dom.minidom import parseString 
    179180    error_messages = [e.firstChild.wholeText for e in parseString(u.read()).getElementsByTagName('messages')[0].getElementsByTagName('msg')] 
    180     raise ValidationError, "Valid HTML is required. Specific errors are:\n%s" % "\n".join(error_messages) 
     181    raise ValidationError, _("Valid HTML is required. Specific errors are:\n%s") % "\n".join(error_messages) 
    181182 
    182183def isWellFormedXml(field_data, all_data): 
     
    185186        parseString(field_data) 
    186187    except Exception, e: # Naked except because we're not sure what will be thrown 
    187         raise ValidationError, "Badly formed XML: %s" % str(e) 
     188        raise ValidationError, _("Badly formed XML: %s") % str(e) 
    188189 
    189190def isWellFormedXmlFragment(field_data, all_data): 
     
    195196        u = urllib2.urlopen(field_data) 
    196197    except ValueError: 
    197         raise ValidationError, "Invalid URL: %s" % field_data 
     198        raise ValidationError, _("Invalid URL: %s") % field_data 
    198199    except: # urllib2.HTTPError, urllib2.URLError, httplib.InvalidURL, etc. 
    199         raise ValidationError, "The URL %s is a broken link." % field_data 
     200        raise ValidationError, _("The URL %s is a broken link.") % field_data 
    200201 
    201202def isValidUSState(field_data, all_data): 
     
    203204    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'] 
    204205    if field_data.upper() not in states: 
    205         raise ValidationError, "Enter a valid U.S. state abbreviation." 
     206        raise ValidationError, _("Enter a valid U.S. state abbreviation.") 
    206207 
    207208def hasNoProfanities(field_data, all_data): 
     
    218219        from django.utils.text import get_text_list 
    219220        plural = len(words_seen) > 1 
    220         raise ValidationError, "Watch your mouth! The word%s %s %s not allowed here." % \ 
     221        raise ValidationError, _("Watch your mouth! The word%s %s %s not allowed here.") % \ 
    221222            (plural and 's' or '', 
    222223            get_text_list(['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1]) for i in words_seen], 'and'), 
     
    226227    def __init__(self, other_field_name, error_message=None): 
    227228        self.other = other_field_name 
    228         self.error_message = error_message or "This field must match the '%s' field." % self.other 
     229        self.error_message = error_message or gettext_lazy("This field must match the '%s' field.") % self.other 
    229230        self.always_test = True 
    230231 
     
    245246 
    246247class RequiredIfOtherFieldNotGiven: 
    247     def __init__(self, other_field_name, error_message="Please enter something for at least one field."): 
     248    def __init__(self, other_field_name, error_message=gettext_lazy("Please enter something for at least one field.")): 
    248249        self.other, self.error_message = other_field_name, error_message 
    249250        self.always_test = True 
     
    254255 
    255256class RequiredIfOtherFieldsGiven: 
    256     def __init__(self, other_field_names, error_message="Please enter both fields or leave them both empty."): 
     257    def __init__(self, other_field_names, error_message=gettext_lazy("Please enter both fields or leave them both empty.")): 
    257258        self.other, self.error_message = other_field_names, error_message 
    258259        self.always_test = True 
     
    265266class RequiredIfOtherFieldGiven(RequiredIfOtherFieldsGiven): 
    266267    "Like RequiredIfOtherFieldsGiven, but takes a single field name instead of a list." 
    267     def __init__(self, other_field_name, error_message="Please enter both fields or leave them both empty."): 
     268    def __init__(self, other_field_name, error_message=gettext_lazy("Please enter both fields or leave them both empty.")): 
    268269        RequiredIfOtherFieldsGiven.__init__(self, [other_field_name], error_message) 
    269270 
     
    272273        self.other_field = other_field 
    273274        self.other_value = other_value 
    274         self.error_message = error_message or "This field must be given if %s is %s" % (other_field, other_value) 
     275        self.error_message = error_message or gettext_lazy("This field must be given if %s is %s") % (other_field, other_value) 
    275276        self.always_test = True 
    276277 
     
    283284        self.other_field = other_field 
    284285        self.other_value = other_value 
    285         self.error_message = error_message or "This field must be given if %s is not %s" % (other_field, other_value) 
     286        self.error_message = error_message or gettext_lazy("This field must be given if %s is not %s") % (other_field, other_value) 
    286287        self.always_test = True 
    287288 
     
    301302    def __init__(self, field_name, prefix, error_message): 
    302303        self.field_name, self.prefix = field_name, prefix 
    303         self.error_message = error_message or "Duplicate values are not allowed." 
     304        self.error_message = error_message or gettext_lazy("Duplicate values are not allowed.") 
    304305 
    305306    def __call__(self, field_data, all_data): 
     
    324325        val = log(int(field_data)) / log(self.power_of) 
    325326        if val != int(val): 
    326             raise ValidationError, "This value must be a power of %s." % self.power_of 
     327            raise ValidationError, _("This value must be a power of %s.") % self.power_of 
    327328 
    328329class IsValidFloat: 
     
    335336            float(data) 
    336337        except ValueError: 
    337             raise ValidationError, "Please enter a valid decimal number." 
     338            raise ValidationError, _("Please enter a valid decimal number.") 
    338339        if len(data) > (self.max_digits + 1): 
    339             raise ValidationError, "Please enter a valid decimal number with at most %s total digit%s." % \ 
     340            raise ValidationError, _("Please enter a valid decimal number with at most %s total digit%s.") % \ 
    340341                (self.max_digits, self.max_digits > 1 and 's' or '') 
    341342        if '.' in data and len(data.split('.')[1]) > self.decimal_places: 
    342             raise ValidationError, "Please enter a valid decimal number with at most %s decimal place%s." % \ 
     343            raise ValidationError, _("Please enter a valid decimal number with at most %s decimal place%s.") % \ 
    343344                (self.decimal_places, self.decimal_places > 1 and 's' or '') 
    344345 
     
    350351    def __init__(self, min_size=None, max_size=None, min_error_message=None, max_error_message=None): 
    351352        self.min_size, self.max_size = min_size, max_size 
    352         self.min_error_message = min_error_message or "Make sure your uploaded file is at least %s bytes big." % min_size 
    353         self.max_error_message = max_error_message or "Make sure your uploaded file is at most %s bytes big." % min_size 
     353        self.min_error_message = min_error_message or gettext_lazy("Make sure your uploaded file is at least %s bytes big.") % min_size 
     354        self.max_error_message = max_error_message or gettext_lazy("Make sure your uploaded file is at most %s bytes big.") % min_size 
    354355 
    355356    def __call__(self, field_data, all_data): 
     
    364365    should be in string format, not already compiled. 
    365366    """ 
    366     def __init__(self, regexp, error_message="The format for this field is wrong."): 
     367    def __init__(self, regexp, error_message=gettext_lazy("The format for this field is wrong.")): 
    367368        self.regexp = re.compile(regexp) 
    368369        self.error_message = error_message 
     
    379380    specify one on instantiation. 
    380381    """ 
    381     def __init__(self, validator_list=[], error_message="This field is invalid."): 
     382    def __init__(self, validator_list=[], error_message=gettext_lazy("This field is invalid.")): 
    382383        self.validator_list = validator_list 
    383384        self.error_message = error_message 
     
    414415            info = urllib2.urlopen(field_data).info() 
    415416        except (urllib2.HTTPError, urllib2.URLError): 
    416             raise URLMimeTypeCheck.CouldNotRetrieve, "Could not retrieve anything from %s." % field_data 
     417            raise URLMimeTypeCheck.CouldNotRetrieve, _("Could not retrieve anything from %s.") % field_data 
    417418        content_type = info['content-type'] 
    418419        if content_type not in self.mime_type_list: 
    419             raise URLMimeTypeCheck.InvalidContentType, "The URL %s returned the invalid Content-Type header '%s'." % (field_data, content_type) 
     420            raise URLMimeTypeCheck.InvalidContentType, _("The URL %s returned the invalid Content-Type header '%s'.") % (field_data, content_type) 
    420421 
    421422class RelaxNGCompact: 
     
    449450            m = re.search(r'Expected "(.*?)" to terminate element starting on line (\d+)', message) 
    450451            if m: 
    451                 display_errors.append('Please close the unclosed %s tag from line %s. (Line starts with "%s".)' % \ 
     452                display_errors.append(_('Please close the unclosed %s tag from line %s. (Line starts with "%s".)') % \ 
    452453                    (m.group(1).replace('/', ''), m.group(2), lines[int(m.group(2)) - 1][:30])) 
    453454                continue 
    454455            if message.strip() == 'text not allowed here': 
    455                 display_errors.append('Some text starting on line %s is not allowed in that context. (Line starts with "%s".)' % \ 
     456                display_errors.append(_('Some text starting on line %s is not allowed in that context. (Line starts with "%s".)') % \ 
    456457                    (line, lines[int(line) - 1][:30])) 
    457458                continue 
    458459            m = re.search(r'\s*attribute "(.*?)" not allowed at this point; ignored', message) 
    459460            if m: 
    460                 display_errors.append('"%s" on line %s is an invalid attribute. (Line starts with "%s".)' % \ 
     461                display_errors.append(_('"%s" on line %s is an invalid attribute. (Line starts with "%s".)') % \ 
    461462                    (m.group(1), line, lines[int(line) - 1][:30])) 
    462463                continue 
    463464            m = re.search(r'\s*unknown element "(.*?)"', message) 
    464465            if m: 
    465                 display_errors.append('"<%s>" on line %s is an invalid tag. (Line starts with "%s".)' % \ 
     466                display_errors.append(_('"<%s>" on line %s is an invalid tag. (Line starts with "%s".)') % \ 
    466467                    (m.group(1), line, lines[int(line) - 1][:30])) 
    467468                continue 
    468469            if message.strip() == 'required attributes missing': 
    469                 display_errors.append('A tag on line %s is missing one or more required attributes. (Line starts with "%s".)' % \ 
     470                display_errors.append(_('A tag on line %s is missing one or more required attributes. (Line starts with "%s".)') % \ 
    470471                    (line, lines[int(line) - 1][:30])) 
    471472                continue 
    472473            m = re.search(r'\s*bad value for attribute "(.*?)"', message) 
    473474            if m: 
    474                 display_errors.append('The "%s" attribute on line %s has an invalid value. (Line starts with "%s".)' % \ 
     475                display_errors.append(_('The "%s" attribute on line %s has an invalid value. (Line starts with "%s".)') % \ 
    475476                    (m.group(1), line, lines[int(line) - 1][:30])) 
    476477                continue