Aman
Aman

Reputation: 783

conditionally validate fields of a class

I have a class with fields like so

Class

What I'd like to do is create a validator that validates the fields based on the request code.

For example

Request code == N validate name is not null other fields can be null

Request code == NAP validate name, address, and fields

Is there anyway I can define a list of fields to validate per enum so my validator only checks for those fields? How would I achieve this in python?

Upvotes: 0

Views: 43

Answers (1)

Oleh Rybalchenko
Oleh Rybalchenko

Reputation: 8059

It strongly depends on your validator implementation, but in general - yes, you can store a list of fields to validate. There are so many ways to achieve this, for example:

fields = {
'N': ['name'],
'NAP': ['name', 'address', 'phone']
}

And then get respective fields inside a validator:

for field in fields['NAP']:
    value = getattr(your_object, field) 
    # validation logic ...

But note that there are a lot of more flexible ways to validate the object

Upvotes: 1

Related Questions