1

I need to customize required field validation message in sitecore forms. I have tried creating new dictionary and updating value there, but it updates message for every forms. My requirement is to keep default required message for 3 fields and custom message for other fields in same form. How to achieve this.

1
  • That's not possible out of the box. You would need to decompile Sitecore libraries, find where is the code which creates validation messages and replace it with your own implementation.
    – Marek Musielak
    Mar 27, 2023 at 11:54

2 Answers 2

0

I think you need to do some customization to handle this. Let's see how the required validation works OOTB.

The required validator is handled through this processor.

Sitecore.ExperienceForms.Mvc.Pipelines.ValidateSubmit.ValidateRequiredFields

And here is the logic to check the validation.

foreach (Item fieldItem in args.FieldItems)
{
    Item item = fieldItem;
    if (MainUtil.GetBool(item.Fields["Required"]?.Value, false) && (fields == null || fields.All<IViewModel>((Func<IViewModel, bool>) (field => item.ID != ID.Parse(field.ItemId)))))
      args.FormSubmitContext.Errors.Add(new FormActionError()
      {
        ErrorMessage = Translate.Text("{0} is required.", (object) item.Fields["Title"]?.Value)
      });
}

So for each form item or control where the Required field is checked, it shows the validation message and if you change it using dictionary then it will apply to all the form controls.

Here is the field on item.

enter image description here

So I would suggest to extend this processor and update your logic.

For this, you may add a field in the base template of the form controls i.e. /sitecore/templates/System/Forms/Validation Settings as this is inherited to all the form controls and in the code behind get that field and replace error message with your custom one.

It's just a hint but you can do this as per your requirement.

Here is the location of the processor

wwwroot\<your-site-root>\App_Config\Sitecore\ExperienceForms\Sitecore.ExperienceForms.Mvc.config

And this is the processor

<processor type="Sitecore.ExperienceForms.Mvc.Pipelines.ValidateSubmit.ValidateRequiredFields, Sitecore.ExperienceForms.Mvc" />

Also create patch file for your custom one. Hope this helps.

0

You can achieve it by creating a custom validator. You need to create a new class and derive it from RegularExpressionValidation. This will you some functionality concerning regular expression validation.

Custom validator

Three functions need to be overridden:

  1. Initialize: initializes the validator based on the validationModel object

  2. Validate : server side validation based on the value

  3. GetClientValidationRules : registers the client side validation rules

public class CustomValidation : RegularExpressionValidation
{
  public override string RegularExpression => "^[0-9]+$";

  private int MinLength { get; set; }
  private int MaxLength { get; set; }

  public CustomValidation(ValidationDataModel validationItem) : base(validationItem)
  {
  }

  public override void Initialize(object validationModel)
  {
    base.Initialize(validationModel);
    var stringInputViewModel = validationModel as StringInputViewModel;
    if (stringInputViewModel == null) return;
    MinLength = stringInputViewModel.MinLength;
    MaxLength = stringInputViewModel.MaxLength;
    Title = stringInputViewModel.Title;
  }

  public override ValidationResult Validate(object value)
  {
    if (value == null) return ValidationResult.Success;
 
    var num = value.ToString().Length;
    if (num > 0 && (num < MinLength || num > MaxLength))
    {
      return new ValidationResult(FormatMessage(Title));
    }

    var regex = new Regex(RegularExpression, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Compiled);
    var input = (string)value;
    if (string.IsNullOrEmpty(input) || regex.IsMatch(input)) return ValidationResult.Success;
    return new ValidationResult(FormatMessage(Title));
  }

  public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
  {
    if (MaxLength > 0)
        yield return new ModelClientValidationStringLengthRule(FormatMessage(Title), MinLength, MaxLength);

    yield return new ModelClientValidationRegexRule(FormatMessage(Title), new Regex(RegularExpression, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Compiled).ToString());
  }
}

Compile the code and publish the dll to the website, where we will add the validator to the configuration in Sitecore.

Sitecore Forms configuration

Open the Content Editor and go to the Forms section in Settings: /sitecore/system/Settings/Forms/Validations. Create a new item of type Validation (or copy an existing and update the fields).

You need to fill in the type (e.g. "Forms.CustomValidation,Forms") and a message. The message has to contain "{0}" as this will be replaced with the title of the field in the code - so e.g. {0} is not a valid entry for this field. Also, do not forget to create a version in every language of your site and translate the message.

Now we need to attach the validator to the field types in order to make it visible when selecting a validator. Go to the Field Types section and let's take the single-line text field: /sitecore/system/Settings/Forms/Field Types/Basic/Single-Line Text. Find the Allowed Validations field and your custom validator to the selected ones.

enter image description here

That's it.. if you now go to a form and select a single-line text field, you will be able to select your newly created validator.

Credit to @Gatogordo Reference Link: Sitecore forms custom validation

Hope it helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.