0

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?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.