2

I've written a series of RegexValidator definitions that I call on django model inputs. Here is an example:

def fein_validator(value):
    err = None
    for validator in FEIN_VALIDATOR:
        try:
            validator(value)
            return value
        except ValidationError as exc:
            err = exc
    raise err

For reference the FEIN_VALIDATOR for this method is below. Note that in this example there is only a single item, I have other validators that have multiple items (hence the for loop):

FEIN_VALIDATOR = [
    RegexValidator(r'^\d{2}-\d{7}$')
    ]

The method works perfectly and throws an error when it's supposed to. But, the error it throws is Enter a valid value. and I would like to customize the return to be more specific.

I've tried versions of this and this. But these all assume that there is only one pass. I'm trying to run through a series of validators using a for loop.

Question 1: does the method construction I'm using work for this - or should there be a separate method for each validation? [whereby I can add custom messaging.]

Question 2: if this does work, how do I change the error message raised to a custom message?

1 Answer 1

1

EDIT 1: Added comment

Yes, your method work perfect.

EDIT 2: Added custom error message model link

custom error messages with Model Form

  def fein_validator(value):
        err = None
        for validator in FEIN_VALIDATOR:
            try:
                validator(value)
                return value
            except ValidationError:
                raise ValidationError({'field_name': ["error message",]})
Sign up to request clarification or add additional context in comments.

3 Comments

This throws TypeError: exceptions must derive from BaseException. I did a little more searching but didn't see why the type error would be thrown... ?
Throws AttributeError: 'ValidationError' object has no attribute 'error_list'. I found this which makes sense, the error is being thrown from a Model which is being populated through a CreateView class instance. I've tried using both the NON_FIELD_ERRORS (which is what I would expect to work) and the model field name ('filed_name') - but they both throw the same error. I'm guessing that my reference to the model field name is wrong - what specifically is the field_name reference to?
After spending more time with the answer above, I realized that there was a bracketing format error (error is now fixed in the answer above) and it works as advertised. Thanks.

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.