How to add custom validation with a FormItem-getter
-
30-06-2021 - |
Question
I need to validate a field as a Zip code and I want to use the FormItem
-getter that was generated for the table I'm building a form for. There's no "GetZipCodeZipFormItem
" FormItem
getter being generated but I've noticed you can validate a Zip code with the Validator
class. I would just add it manually with the my DataModification
but I don't have a reference to the PostBackValueDictionary
needed to get the value from the FormItem
's control.
How can I validate this FormItem
as a Zip code?
Solution
Assuming yourModObject.ZipCode
is a string:
yourModObject.GetZipCodeFormItem(
true,
( value, label ) => new EwfTextBox( value ),
( control, pbv, subject, validator ) =>
validator.GetZipCode( new ValidationErrorHandler( subject ),
control.GetPostBackValue( pbv ),
true ).FullZipCode,
value: "",
validationList: yourDataModification )
Another way to do it is:
yourModObject.GetZipCodeTextFormItem(
true,
true, // allow empty
value: "",
additionalValidationMethod: ( subject, validator ) =>
yourModObject.ZipCode = validator.GetZipCode( new ValidationErrorHandler( subject ),
yourModObject.ZipCode,
true ).FullZipCode,
validationList: yourDataModification )
One drawback to the second approach is that the primary validation (i.e. the logic that stores a value in the mod object) is not aware that it's a ZIP Code that is being entered, so if, for example, your database field had a limit of nine characters (to accommodate a ZIP+4) and the user entered "12345-1234", primary validation would fail because the dash pushes the string over the length limit. You wouldn't even get to the additional validation method. This problem doesn't exist with the first approach.