ICustomFormFieldValidator

By implementing the ICustomFormFieldValidator, you can create your own validation rules for form fields.  This can be useful when the built-in field validators are not enough.  An example would be to create complex conditional validation rules like enforcing certain fields where other fields contain certain values.

The interface only has one method that needs to be implemented, the Validate() method.  The value of the field which the validator is assigned to is provided as an argument, and also the formValues collection which contains data from all other fields present in the form.

Interface declaration

public interface ICustomFormFieldValidator
{
	string Validate(object fieldValue, Dictionary<string, object> formValues);
}

Example

In this simple example, we are checking if the field contains a question, simply by checking if it ends with a question mark.

[DisplayName("Enforce question mark")]
[Description("Will only pass validation if the field value ends with a question mark")]
public class EnforceQuestionFieldValidator : ICustomFormFieldValidator
{
	public string Validate(object fieldValue, Dictionary<string, object> formValues)
	{
		var value = (fieldValue as string) ?? "";
		if (!value.EndsWith("?"))
		{
			return "Hey, this needs to end with a question mark!";
		}
			
		return "";
	}
}

Registration

This is how the implementation is registered into the DI container in Veva, this should be done in your module config file (The class which implements IModule).

public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
	services.AddNamed<ICustomFormFieldValidator, EnforceQuestionFieldValidator>(ServiceLifetime.Transient);
}

Usage

To use a custom field validator, click the field component you wish to assign it to, expand the "Validation" section in the settings and your validator should be shown in the list of custom validators.  Click the "Plus" button to apply it.