Jeet Patel
Jeet Patel

Reputation: 1241

How to make Pydantic raise an exception right away

I wrote a Pydantic model to validate API payload.

The payload has 2 attributes emailId as list and role as str

{
    "emailId": [], 
    "role":"Administrator"
}

I need to perform two validation on attribute email -

  1. emailId must not be empty.
  2. emailId must not contain emails from x, y, z domains.

Hence to accomplish this I wrote 2 validation methods for emailId as shown below -

class PayloadValidator(BaseModel):

    emailId: List[str]
    role: str

    @validator("emailId")
    def is_email_list_empty(cls, email):
        if not email_id:
            raise ValueError("Email list is empty.")
        return email_id

    @validator("emailId")
    def valid_domains(cls, emailId):
        pass

The problem here is that if the emailId list is empty then the validators does not raise ValueError right away. It waits for all the validation method to finish execution and this is causing some serious problems to me.

Is there a way I can make it happen?

Upvotes: 5

Views: 12317

Answers (1)

alex_noname
alex_noname

Reputation: 32233

If you have checks, the failure of which should interrupt the further validation, then put them in the pre=True root validator. Because field validation will not occur if pre=True root validators raise an error.

For example:

class PayloadValidator(BaseModel):

    emailId: List[str]
    role: str

    @root_validator(pre=True)
    def root_validate(cls, values):
        if not values['emailId']:
            raise ValueError("Email list is empty.")
        return values

    @validator("emailId")
    def valid_domains(cls, emailId):
        return emailId

Upvotes: 5

Related Questions