Skip to content

Instantly share code, notes, and snippets.

@manuelep
Last active May 13, 2021 07:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manuelep/19a0e9ab6723086fdbf1ffa8e858a5f9 to your computer and use it in GitHub Desktop.
Save manuelep/19a0e9ab6723086fdbf1ffa8e858a5f9 to your computer and use it in GitHub Desktop.
custom pydal/py4web/web2py validators
# -*- coding: utf-8 -*-
from pydal.validators import Validator, IS_MATCH, ValidationError
class IS_NOT(Validator):
""" A not validatro is like a not joke... NOT! """
def __init__(self, validator, *args, error_message="Invalid expression", **kwargs):
super(IS_NOT, self).__init__()
self.__validator = validator(*args, **kwargs)
self.error_message = error_message
def validate(self, value, record_id=None):
value_, message = self.__validator(value, record_id=None)
if message is None:
raise ValidationError(self.translator(self.error_message))
else:
return value_
class HAS_NOT_URL(IS_NOT):
""" A validator for strings that must not contain URLs """
# Regex courtesy of Raul ;-)
# https://groups.google.com/g/web2py/c/nSB6LOe5NgM/m/gLsKr_SeFQAJ
URLREGEX = '(?i)\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:\'\\".,<>?«»“”‘’]))'
def __init__(self, error_message="URL not allowed here!"):
super(HAS_NOT_URL, self).__init__(
IS_MATCH,
expression = f".*{self.URLREGEX}.*",
error_message = error_message
)
IS_NOT_SPAM = HAS_NOT_URL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment