Adding A Server-Side Notification Handler To Umbraco Forms
See an example of validating a form server-side
Form validation notification
using System.Linq;
using Microsoft.AspNetCore.Http;
using Umbraco.Cms.Core.Events;
using Umbraco.Forms.Core.Models;
using Umbraco.Forms.Core.Services.Notifications;
namespace MyFormsExtensions
{
/// <summary>
/// Catch form submissions before being saved and perform custom validation.
/// </summary>
public class FormValidateNotificationHandler : INotificationHandler<FormValidateNotification>
{
public void Handle(FormValidateNotification notification)
{
// If needed, be selective about which form submissions you affect.
if (notification.Form.Name == "Form Name")
{
// Check the ModelState
if (notification.ModelState.IsValid == false)
{
return;
}
// A sample validation
var email = GetPostFieldValue(notification.Form, notification.Context, "email");
var emailConfirm = GetPostFieldValue(notification.Form, notification.Context, "verifyEmail");
// If the validation fails, return a ModelError
if (email.ToLower() != emailConfirm.ToLower())
{
notification.ModelState.AddModelError(GetPostField(notification.Form, "verifyEmail").Id.ToString(), "Email does not match");
}
}
}
private static string GetPostFieldValue(Form form, HttpContext context, string key)
{
Field field = GetPostField(form, key);
if (field == null)
{
return string.Empty;
}
return context.Request.HasFormContentType && context.Request.Form.Keys.Contains(field.Id.ToString())
? context.Request.Form[field.Id.ToString()].ToString().Trim()
: string.Empty;
}
private static Field GetPostField(Form form, string key) => form.AllFields.SingleOrDefault(f => f.Alias == key);
}
}Service notifications
Backoffice entry rendering events
Last updated
Was this helpful?