DEV Community

Cover image for Umbraco Forms Fieldtype with custom client and serverside validation
Tim Geyssens
Tim Geyssens

Posted on

Umbraco Forms Fieldtype with custom client and serverside validation

Umbraco Forms allows you to add custom fieldtypes, I won´t go into detail on how to do that since you can find detailed docs over at our umbraco

As you can see it is also easy to add server side validation on a fieldtype level.

Let´s say you want have a phone number field and validate the number agains on api (to make sure it exists)

 public override IEnumerable<string> ValidateField(Form form, Field field, IEnumerable<object> postedValues, HttpContext context, IPlaceholderParsingService placeholderParsingService)
        {
            var returnStrings = new List<string>();

            var service = new NumverifyService();

            if (postedValues.Any() && !service.Verify(postedValues.First().ToString()))
            {
                returnStrings.Add(ValidPhoneNumber);
            }

            returnStrings.AddRange(base.ValidateField(form, field, postedValues, context, placeholderParsingService));

            return returnStrings;
        }

Enter fullscreen mode Exit fullscreen mode

So that is the server side validation sorted.

For client side I´ll call the same NumverifyService from a api controller

    public class FormApiController : UmbracoApiController
    {
        private readonly NumverifyService _service;

        public FormApiController()
        {
            _service = new NumverifyService();
        }


        [HttpGet]
        public bool Check()
        {

            return _service.Verify(HttpContext.Current.Request.Params[0]);
        }
    }
Enter fullscreen mode Exit fullscreen mode

Once thing to notice here is that I don´t use a param in the check method since form fields are named based on a guid...not on the alias of the form field. So I´ll just fetch the first request param.

So now how do you hook this up with the custom fieldtype? And do remove validation (Remote Validation is a technique that uses client side script to validate user input on the server without posting the entire form)

Since by default forms is using unobtrusive validation it can be handled by adding these attributes to the element. in the form field razor view

       data-val-remote="Not a valid phone number"
       data-val-remote-additionalfields="*.@Model.Name"
       data-val-remote-url="/Umbraco/Api/FormApi/Check/"
Enter fullscreen mode Exit fullscreen mode

the error message, the field to send to the remote url and the url of the api method.

So no need for additional js...

Top comments (0)