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 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 = GetFieldValue(notification.Form, "email");
var emailConfirm = GetFieldValue(notification.Form, "verifyEmail");
// If the validation fails, return a ModelError.
if (email.ToLower() != emailConfirm.ToLower())
{
// Standard form POST renders validation messages keyed by field Id,
// while the headless API returns errors keyed by field alias.
Field verifyEmailField = GetField(notification.Form, "verifyEmail")!;
var errorKey = notification.Context.Request.HasFormContentType
? verifyEmailField.Id.ToString()
: verifyEmailField.Alias;
notification.ModelState.AddModelError(errorKey, "Email does not match");
}
}
}
/// <summary>
/// Gets the submitted value for a field by its alias.
/// </summary>
/// <remarks>
/// Field.Values is populated before the notification fires in both submission paths
/// (standard form POST and headless API JSON submissions), making it the reliable way
/// to access submitted values regardless of how the form was submitted.
/// </remarks>
private static string GetFieldValue(Form form, string alias)
{
Field? field = GetField(form, alias);
return field?.Values.FirstOrDefault()?.ToString()?.Trim() ?? string.Empty;
}
private static Field? GetField(Form form, string alias)
=> form.AllFields.SingleOrDefault(f => f.Alias == alias);
}
}Service notifications
Backoffice entry rendering events
Last updated
Was this helpful?