Re: Usage of if_empty
Ian Bicking <[email protected]>
| Newsgroups | gmane.comp.python.formencode |
|---|---|
| Message-ID | <[email protected]> |
michelts wrote:
> Good morning guys!
>
> I used to have validators as the above:
>
> class validator(Schema):
> firstName = NotEmpty()
> lastName = NotEmpty(if_empty='anything')
>
> I updated FormEncode to the version 0.5.1 and now this is not working,
> I look at the code and I see if_empty is no more supported, but the
> docs on the formencode.org still have reference to if_empty.
>
> I solve my problem for know changing my validator to the above:
>
> class validator(Schema):
> firstName = NotEmpty()
> lastName = String()
>
> But this way I can't set a specific lastName if it is not specified,
> this is usefull in some situations. The if_empty keyword wont be
> supported or this is a bug?
This is a bug. There was a change in FormEncode to handle empty values
differently, generally passing them through. Perhaps this shortcutted
the if_empty test.
However, the code looks right to me (in FancyValidator):
def to_python(self, value, state=None):
try:
if self.strip and isinstance(value, (str, unicode)):
value = value.strip()
if self.is_empty(value):
if self.not_empty:
raise Invalid(self.message('empty', state), value,
state)
else:
if self.if_empty is not NoDefault:
return self.if_empty
else:
return self.empty_value(value)
So, we test if the value is empty, and then test not_empty. Then we use
if_empty.
I do think NotEmpty(if_empty='anything') may have broken, as the
not_empty/if_empty tests have been switched around. Really it doesn't
make sense to have both set, so I guess I wouldn't call that a bug.
String(if_empty='anything') should work. If it doesn't, reply and we'll
try to figure it out.