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?

Bill Armstrong
  • 1,615
  • 3
  • 23
  • 47

1 Answers1

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",]})
Borishi
  • 38
  • 6
  • 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... ? – Bill Armstrong May 11 '18 at 04:29
  • Throws `AttributeError: 'ValidationError' object has no attribute 'error_list'`. I found [this](https://stackoverflow.com/questions/45869212/how-to-properly-throw-a-validationerror-in-django) 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? – Bill Armstrong May 11 '18 at 05:20
  • 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. – Bill Armstrong May 11 '18 at 20:33