<commit_before>import re


__all__ = (
    'Email', 'email', 'EqualTo', 'equal_to', 'IPAddress', 'ip_address',
    'Length', 'length', 'Optional', 'optional', 'Required', 'required',
    'Regexp', 'regexp', 'URL', 'url',
)


class ValidationError(ValueError):
    """
    Raised when a validator fails to validate its input.
    """
    def __init__(self, message=u'', *args, **kwargs):
        ValueError.__init__(self, message, *args, **kwargs)


class StopValidation(ValidationError):
    """
    Causes the validation chain to stop.

    If StopValidation is raised, no more validators in the validation chain are
    called. If raised with a message, the message will be added to the errors
    list.
    """
    def __init__(self, message=u'', *args, **kwargs):
        ValidationError.__init__(self, message, *args, **kwargs)


class EqualTo(object):
    """
    Compares the values of two fields.

    :param fieldname:
        The name of the other field to compare to.
    :param message:
        Error message to raise in case of a validation error.
    """
    def __init__(self, fieldname, message=None):
        self.fieldname = fieldname
        self.message = message or u'Field must be equal to %s' % fieldname

    def __call__(self, form, field):
        other = getattr(form, self.fieldname, None)
        if not other:
            raise ValidationError(u"Invalid field name '%s'" % self.fieldname)
        elif field.data != other.data:
            raise ValidationError(self.message)


class IPAddress(object):
    """
    Validates an IP(v4) address.

    :param message:
        Error message to raise in case of a validation error.
    """
    def __init__(self, message=u'Invalid IP address.'):
        self.message = message
    
    def __call__(self, form, field):
        if not re.match(r'^([0-9]{1,3}\.){3}[0-9]{1,3}$', field.data):
            raise ValidationError(self.message)


class Length(object):
    """
    Validates the length of a string.

    :param min:
        The minimum required length of the string. If not provided, minimum
        length will not be checked.        
    :param max:
        The maximum length of the string. If not provided, maximum length
        will not be checked.
    :param message:
        Error message to raise in case of a validation error. A default
        containing min and max length is provided.
    """
    def __init__(self, min=-1, max=-1, message=None):
        self.min = min
        self.max = max
        self.message = message or u'Field must be between %i and %i characters long.' % (min, max)
    
    def __call__(self, form, field):
        l = field.data and len(field.data) or 0
        if l < self.min or self.max != -1 and l > self.max:
            raise ValidationError(self.message)


class Optional(object):
    """
    Allows empty input and stops the validation chain from continuing.
    """
    field_flags = ('optional', )

    def __call__(self, form, field):
        if not field.data or isinstance(field.data, basestring) and not field.data.strip():
            raise StopValidation()


class Required(object):
    """
    Validates that the field contains data. This validator will stop the
    validation chain on error.

    :param message:
        Error message to raise in case of a validation error.
    """
    field_flags = ('required', )

    def __init__(self, message=u'This field is required.'):
        self.message = message

    def __call__(self, form, field):
        if not field.data or isinstance(field.data, basestring) and not field.data.strip():
            raise StopValidation(self.message)


class Regexp(object):
    """
    Validates the field against a user provided regexp.

    :param regex:
        The regular expression string to use. Can also be a compiled regular
        expression pattern.
    :param flags:
        The regexp flags to use, for example re.IGNORECASE. Ignored if
        `regex` is not a string.  
    :param message:
        Error message to raise in case of a validation error.
    """
    def __init__(self, regex, flags=0, message=u'Invalid input.'):
        self.regex = isinstance(regex, basestring) and re.compile(regex, flags) or regex
        self.message = message
    
    def __call__(self, form, field):
        if not self.regex.match(field.data or ''):
            raise ValidationError(self.message)


class Email(Regexp):
    """
    Validates an email address. Note that this uses a very primitive regular
    expression and should only be used in instances where you later verify by
    other means, such as email activation or lookups.

    :param message:
        Error message to raise in case of a validation error.
    """
    def __init__(self, message=u'Invalid email address.'):
        super(Email, self).__init__(r'^.+@[^.].*\.[a-z]{2,}$', re.IGNORECASE, message)


class URL(Regexp):
    """
    Simple regexp based url validation. Much like the email validator, you
    probably want to validate the url later by other means if the url must 
    resolve.

    :param require_tld:
        If true, then the domain-name portion of the URL must contain a .tld
        suffix.  Set this to false if you want to allow domains like 
        `localhost`.
    :param message:
        Error message to raise in case of a validation error.
    """
    def __init__(self, require_tld=True, message=u'Invalid URL.'):
        regex = r'^[a-z]+://([^/:]+%s|([0-9]{1,3}\.){3}[0-9]{1,3})(:[0-9]+)?(\/.*)?$' % (require_tld and r'\.[a-z]{2,}' or '')
        super(URL, self).__init__(regex, re.IGNORECASE, message)


email = Email
equal_to = EqualTo
ip_address = IPAddress
length = Length
optional = Optional
required = Required
regexp = Regexp
url = URL
<commit_msg>The IP address validator can inherit from Regex, so it might as well.<commit_after>import re


__all__ = (
    'Email', 'email', 'EqualTo', 'equal_to', 'IPAddress', 'ip_address',
    'Length', 'length', 'Optional', 'optional', 'Required', 'required',
    'Regexp', 'regexp', 'URL', 'url',
)


class ValidationError(ValueError):
    """
    Raised when a validator fails to validate its input.
    """
    def __init__(self, message=u'', *args, **kwargs):
        ValueError.__init__(self, message, *args, **kwargs)


class StopValidation(ValidationError):
    """
    Causes the validation chain to stop.

    If StopValidation is raised, no more validators in the validation chain are
    called. If raised with a message, the message will be added to the errors
    list.
    """
    def __init__(self, message=u'', *args, **kwargs):
        ValidationError.__init__(self, message, *args, **kwargs)


class EqualTo(object):
    """
    Compares the values of two fields.

    :param fieldname:
        The name of the other field to compare to.
    :param message:
        Error message to raise in case of a validation error.
    """
    def __init__(self, fieldname, message=None):
        self.fieldname = fieldname
        self.message = message or u'Field must be equal to %s' % fieldname

    def __call__(self, form, field):
        other = getattr(form, self.fieldname, None)
        if not other:
            raise ValidationError(u"Invalid field name '%s'" % self.fieldname)
        elif field.data != other.data:
            raise ValidationError(self.message)


class Length(object):
    """
    Validates the length of a string.

    :param min:
        The minimum required length of the string. If not provided, minimum
        length will not be checked.        
    :param max:
        The maximum length of the string. If not provided, maximum length
        will not be checked.
    :param message:
        Error message to raise in case of a validation error. A default
        containing min and max length is provided.
    """
    def __init__(self, min=-1, max=-1, message=None):
        self.min = min
        self.max = max
        self.message = message or u'Field must be between %i and %i characters long.' % (min, max)
    
    def __call__(self, form, field):
        l = field.data and len(field.data) or 0
        if l < self.min or self.max != -1 and l > self.max:
            raise ValidationError(self.message)


class Optional(object):
    """
    Allows empty input and stops the validation chain from continuing.
    """
    field_flags = ('optional', )

    def __call__(self, form, field):
        if not field.data or isinstance(field.data, basestring) and not field.data.strip():
            raise StopValidation()


class Required(object):
    """
    Validates that the field contains data. This validator will stop the
    validation chain on error.

    :param message:
        Error message to raise in case of a validation error.
    """
    field_flags = ('required', )

    def __init__(self, message=u'This field is required.'):
        self.message = message

    def __call__(self, form, field):
        if not field.data or isinstance(field.data, basestring) and not field.data.strip():
            raise StopValidation(self.message)


class Regexp(object):
    """
    Validates the field against a user provided regexp.

    :param regex:
        The regular expression string to use. Can also be a compiled regular
        expression pattern.
    :param flags:
        The regexp flags to use, for example re.IGNORECASE. Ignored if
        `regex` is not a string.  
    :param message:
        Error message to raise in case of a validation error.
    """
    def __init__(self, regex, flags=0, message=u'Invalid input.'):
        if isinstance(regex, basestring):
            regex = re.compile(regex, flags)
        self.regex = regex 
        self.message = message
    
    def __call__(self, form, field):
        if not self.regex.match(field.data or ''):
            raise ValidationError(self.message)


class Email(Regexp):
    """
    Validates an email address. Note that this uses a very primitive regular
    expression and should only be used in instances where you later verify by
    other means, such as email activation or lookups.

    :param message:
        Error message to raise in case of a validation error.
    """
    def __init__(self, message=u'Invalid email address.'):
        super(Email, self).__init__(r'^.+@[^.].*\.[a-z]{2,}$', re.IGNORECASE, message)


class IPAddress(Regexp):
    """
    Validates an IP(v4) address.

    :param message:
        Error message to raise in case of a validation error.
    """
    def __init__(self, message=u'Invalid IP address.'):
        super(IPAddress, self).__init__(r'^([0-9]{1,3}\.){3}[0-9]{1,3}$', message=message)


class URL(Regexp):
    """
    Simple regexp based url validation. Much like the email validator, you
    probably want to validate the url later by other means if the url must 
    resolve.

    :param require_tld:
        If true, then the domain-name portion of the URL must contain a .tld
        suffix.  Set this to false if you want to allow domains like 
        `localhost`.
    :param message:
        Error message to raise in case of a validation error.
    """
    def __init__(self, require_tld=True, message=u'Invalid URL.'):
        regex = r'^[a-z]+://([^/:]+%s|([0-9]{1,3}\.){3}[0-9]{1,3})(:[0-9]+)?(\/.*)?$' % (require_tld and r'\.[a-z]{2,}' or '')
        super(URL, self).__init__(regex, re.IGNORECASE, message)


email = Email
equal_to = EqualTo
ip_address = IPAddress
length = Length
optional = Optional
required = Required
regexp = Regexp
url = URL

{'fraction_non_alphanumeric': 0.1094553376906318, 'fraction_numerical': 0.004880174291938997, 'mean_word_length': 2.682926829268293, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2720507', 'n_tokens_mistral': 3331, 'n_tokens_neox': 3254, 'n_words': 1231}