Ross Symonds
Ross Symonds

Reputation: 710

Create validation error with two possible conditions

I can create a if not statement with one condition. This works -

if not "ABC124" in voucher:
     raise forms.ValidationError("Invalid Voucher")
return voucher

And this works -

if not "ABC124" in voucher:
     raise forms.ValidationError("Invalid Voucher")
return voucher

But this doesn't work -

 if not "ABC124" in voucher or if not "ABC123" in voucher:
      raise forms.ValidationError("Invalid Voucher")
 return voucher

And this doesn't work -

if not "ABC124" in voucher or not "ABC123" in voucher :
     raise forms.ValidationError("Invalid Voucher")
return voucher

How do I make an if statement with two conditions?

Upvotes: 1

Views: 28

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476977

Because of the De Morgan's laws [wiki], you need to use and as an operator, not or:

if 'ABC124' not in voucher and 'ABC123' not in voucher :
     raise forms.ValidationError('Invalid Voucher')
return voucher

So only if the vouches does not contain 'ABC124' and it does not contain 'ABC123' either, it will raise an error.


Note: It is more readable to write x not in y than to write not x in y.

Upvotes: 1

Related Questions