Nibble

Archive for March, 2014

Contour, adding custom validation without using code first 13

Just a quick post to share the answer to a question I got on the forum.

So as you can see in the code first examples, creating Contour forms code first also allows for an easy way to add extra (custom validation) http://www.nibble.be/?p=205

But there is also a way to add custom rules when you are designing the form in the UI.

There is an event you can hook into to add validation errors, a typical case for this would be a password and repeast password field where you need to make sure the input is the same.

image

So in the form designer these are just 2 password fields with no link

image

And to add the extra validation rules

    public class ContourValidation : ApplicationEventHandler
    {
        protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            FormRenderController.FormValidate += FormRenderController_FormValidate;
        }
 
        void FormRenderController_FormValidate(object sender, Umbraco.Forms.Mvc.FormViewEventArgs e)
        {
            if (e.Form.Name == "FormWithExtraValidation")
            {
                var s = sender as Controller;
                if (s != null)
                {
                    var pwf = e.Form.AllFields.SingleOrDefault(f => f.Caption == "Password").Id.ToString();
                    var rpwf = e.Form.AllFields.SingleOrDefault(f => f.Caption == "Repeat password").Id.ToString();
 
                    var password = e.Context.Request[pwf];
                    var repeatpassword = e.Context.Request[rpwf];
 
                    if(password != repeatpassword)
                        s.ModelState.AddModelError(rpwf, "passwords don’t match");
                    
                }
            }
        }
    }

So hook into the FormValidate event of the FormRenderController that will fire when a form validates

You can then add extra model errors to the modelstate