1

I need to add validation for mobile number and email field, if user will do enable sms_alert/mail_alert, then mobile_numbers/emails must be a "required field" and if no then user may or may not enter mobile_numbers/emails my pydantic model is 

class Info(BaseModel):    
   enable_mail_alert :str = 'n'    
   enable_sms_alert: str = 'n'    
   emails: str    ``
   mobile_numbers: str

@validator('mobile_numbers')    
 def clean_space(cls,mobile_numbers,enable_sms_alert):        
   if  'enable_sms_alert' == 'y':            
       if mobile_numbers=='' or mobile_numbers==None or mobile_numbers=='None':                
           raise ValueError('mobile_numbers field is required')

Above code giving me error as pydantic.errors.ConfigError: Invalid signature for validator <function info_update.clean_space at 0x7f9316664940>: (cls, mobile_numbers, enable_sms_alert), should be: (cls, value, values, config, field), "values", "config" and "field" are all optional.

  • read the [docs](https://docs.pydantic.dev/usage/validators/). The function head of the validator function does not conform to the expected format as stated in the error message. – Plagon Feb 23 '23 at 10:37
  • The signature of your `clean_space` function needs to conform to the format expected by Pydantic - so `(cls, value, values, config, field)` - in your case you probably only need `clean_space(cls, value, values)`, so that you can inspect the `enable_sms_alert` field. I'd also suggest changing the `enable_sms_alert` field to be a boolean field instead of a string, so that it's clearer that it can only contain true/false. – MatsLindh Feb 23 '23 at 14:38
  • Please have a look at [this answer](https://stackoverflow.com/a/71258131/17865804) – Chris Feb 24 '23 at 07:12
  • Does this answer your question? [How to validate more than one field of a Pydantic model?](https://stackoverflow.com/questions/61392633/how-to-validate-more-than-one-field-of-a-pydantic-model) – Chris Mar 15 '23 at 11:26

2 Answers2

0

Try this:

@validator('mobile_numbers')    
 def clean_space(cls, value, values):        
   if  values.get('enable_sms_alert') == 'y' and value in ["", None, 'None']:                
           raise ValueError('mobile_numbers field is required')

You have mobile_numbers in your value variable and all other class variables in your values such as enable_mail_alert, enable_sms_alert, etc.

Artem Strogin
  • 176
  • 1
  • 6
0

I think you should use values in function clean_space from which you can access any other variable than mobile_numbers

    @validator('mobile_numbers')  
        def clean_space(cls,mobile_numbers,values):
           if values['enable_sms_alert'] == 'y':  
              if mobile_numbers=='' or mobile_numbers==None or mobile_numbers=='None':  
                    raise ValueError('mobile_numbers field is required')
SternK
  • 11,649
  • 22
  • 32
  • 46