Custom validation in EPiServer XForm
Sometimes you might want to add some validation for the user input in a XForm. I recently did this for a customer of mine. If you can manage your validation with regular expressions you’re done. Just add a class to your project like this:
This validates the input as 24h time and will show up in the XForm editors “Validate as” drop down.
If you need to validate more complex things, like in my case, a dynamic range of real numbers and a Swedish social security number (personnummer), regular expressions isn’t enough and EPiServer doesn’t offer you any other way to do custom validation other then regular expressions. After discussions with my customer and the fact that the editors should be able to dynamically add a validation range we decided to use the “CSS class” property of the XForm controls as the place for the editor to state a validation range. We agreed on this form:
“<prefix><real number>|<real number>”
For example: “Range:-5,2|16,7” or “Range:0|100”
This could of course be solved with regular expressions but my customer would then need hundreds of ranges to choose from which would be very unpractical. Since the “CSS class” property isn’t used we decided to go for the approach above. A more elegant solution would be to add a extra field in the XForm editor, but then you need to reflect and modify EPiServer.XForm.dll which has its drawbacks.
We do the validation in “BeforeSubmitPostedData”. Hook up the event as usual. I also added a asp:BulletedList to display messages to the user.
Here is an example of how it looks (we also see other validations and a date picker, but that’s another post)