How to Validate Input with Regex in Python
The aim of this page📝 is to remember how to simply add an input validation and raise ValueError
in Python in case it does not conform to my needs.
2 min readNov 3, 2022
My script needs to take a client tag in the form of
com_acme
The underscore is essential and it cannot be the .
as in com.acme
Sure, I can make the script more robust by doing the replacement in case the input arrives with .
instead of _
but I want something more strict and explicit as this is a dialog process and colleagues should be informed about proper syntax for reasons irrelevant here.
Just memorize ‘if not re.match(<regex>, <input> ): raise ValueError(<error_message>)’
- use
re
regex module - use
match
method. There is a difference betweensearch
andmatch
methods (https://docs.python.org/3/library/re.html#search-vs-match) re.match()
returns eithernull
for no match or a match object (https://docs.python.org/3/library/re.html#re.match)- the content of the match object is irrelevant for this, as we only want
true
/false
- of course, we can use
truthy/falsy
testing →null
isfalsy
and the match object istruthy
Match objects always have a boolean value of True. Since match() and search() return None when there is no match, you can test whether there was a match with a simple if statement
- https://docs.python.org/3/library/re.html#match-objects
- for incorrect input, raise ValueError and provide a proper exception message (link to my docs on exception handling)
- the method uses the syntax
re.match(<regex>, <input>)
- in sum (not explaining the simple regex here, also is not the most robust one but does the job), the function looks like this
import re
def validate_client_input(client: str) -> None:
if not re.match("^\w{1,}_\w{1,}$", client):
raise ValueError(
"Client name has to have the form of com_acme (note the underscore separator)")