Ticket #17637: pattern_charfield.patch

File pattern_charfield.patch, 1.4 KB (added by karthikabinav, 3 years ago)

Supply accepted characters as a regular expression in CharField forms. Uses HTML5 attribute 'pattern' to provide the client side validation.

  • django/forms/fields.py

     
    182182        return result
    183183
    184184class CharField(Field):
    185     def __init__(self, max_length=None, min_length=None, *args, **kwargs):
    186         self.max_length, self.min_length = max_length, min_length
     185    # Supply the validation pattern as Regular Expression
     186    def __init__(self, max_length=None, min_length=None,pattern=None, *args, **kwargs):
     187        self.max_length, self.min_length, self.pattern = max_length, min_length, pattern
    187188        super(CharField, self).__init__(*args, **kwargs)
    188189        if min_length is not None:
    189190            self.validators.append(validators.MinLengthValidator(min_length))
    190191        if max_length is not None:
    191192            self.validators.append(validators.MaxLengthValidator(max_length))
    192 
     193       
    193194    def to_python(self, value):
    194195        "Returns a Unicode object."
    195196        if value in validators.EMPTY_VALUES:
     
    201202        if self.max_length is not None and isinstance(widget, (TextInput, PasswordInput)):
    202203            # The HTML attribute is maxlength, not max_length.
    203204            attrs.update({'maxlength': str(self.max_length)})
     205            if self.pattern:
     206                attrs.update({'pattern':str(self.pattern)})
    204207        return attrs
    205208
    206209class IntegerField(Field):
Back to Top