Reputation: 8722
I defined a RegexValidator using Django's built-in class. Like as follows:
from django.core.validators import RegexValidator
validate_alphanumeric = RegexValidator(r'^[a-zA-Z0-9]*$', 'Only alphanumeric characters are allowed.')
The issue is that I am using this from outside of the model definition. Like as follows:
try:
validate_alphanumeric("++")
except:
# Somehow get the message defined above, that is get 'Only alphanumeric characters are allowed.'
In other words, if the string passed causes an error, I want to get the message stored in my RegexValidator object definition. How can I do this?
Upvotes: 0
Views: 111
Reputation: 308899
Catch the exception and use the message
attribute of the validation error.
from django.core.exceptions import ValidationError
try:
validate_alphanumeric("++")
except ValidationError as exc:
message = exc.message
Upvotes: 1