You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This means that it's not trivial to ensure that the entire string matches a regex, especially when that regex is complex.
I propose something like this:
classRegexp:
""" 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. :param re_match_type "match" (default), "fullmatch", or "search" """def__init__(self, regex, flags=0, message=None, re_match_type="match":
ifisinstance(regex, str):
regex=re.compile(regex, flags)
self.regex=regexself.message=messageself.re_match_type=re_match_typedef__call__(self, form, field, message=None):
ifself.re_match_type=="match":
match=self.regex.match(field.dataor"")
ifself.re_match_type=="fullmatch":
match=self.regex.fullmatch(field.dataor"")
elifself.re_match_type=="search":
match=self.regex.search(field.dataor"")
else:
raiseValueError("... but how???")
ifmatch:
returnmatchifmessageisNone:
ifself.messageisNone:
message=field.gettext("Invalid input.")
else:
message=self.messageraiseValidationError(message)
Obviously I could make it more "intelligent" with getattr or something, and a real implementation would probably use an enum and do the validation elsewhere, but for the purposes of getting the idea across, the above is sufficient.
Thoughts? Would you mind if I implemented this?
Current workaround:
Make a custom validator akin to:
defvalidate_regexp_fullmatch(regex: str|re.Pattern) ->Callable:
"""A validator very similar to `wtforms.validators.regexp`, except that it uses 'fullmatch'."""message="Regex Match failure"ifisinstance(regex, str):
regex=re.compile(regex)
def_validate(form, field):
match=regex.fullmatch(field.dataor"")
ifmatch:
returnmatchraisewtforms.validators.ValidationError(message)
return_validate
Environment
Python version: 3.12
wtforms version: 3.1.2
The text was updated successfully, but these errors were encountered:
The
regexp
validator usesre.match
:wtforms/src/wtforms/validators.py
Line 352 in bbfb78c
This means that it's not trivial to ensure that the entire string matches a regex, especially when that regex is complex.
I propose something like this:
Obviously I could make it more "intelligent" with
getattr
or something, and a real implementation would probably use an enum and do the validation elsewhere, but for the purposes of getting the idea across, the above is sufficient.Thoughts? Would you mind if I implemented this?
Current workaround:
Make a custom validator akin to:
Environment
The text was updated successfully, but these errors were encountered: