Thursday, April 21, 2022

How to add custom validation

 Case :

We have a start and end date in the field section. I would like to allow my user to select only the future date. how we can do that?

Create a custom class:

using Sitecore.Data.Validators;

using Sitecore.Data.Fields;

using System;

using System.Runtime.Serialization;

 

namespace Foundation.Validation.Validators

{

    public class FutureDateValidator : StandardValidator

    {

        public FutureDateValidator() : base()

        {

        }

 

        public FutureDateValidator(SerializationInfo info, StreamingContext context)

            : base(info, context)

        {

        }

 

        protected override ValidatorResult Evaluate()

        {

            Field field = this.GetField();

            DateTime time = Sitecore.DateUtil.IsoDateToDateTime(field.Value).Date;

            if (time >= DateTime.UtcNow)

            {

                return ValidatorResult.Valid;

            }

            this.Text = this.GetText("The field \"{0}\" should contain a future date", field.DisplayName);

            return ValidatorResult.CriticalError;

        }

        protected override ValidatorResult GetMaxValidatorResult() { return GetFailedResult(ValidatorResult.CriticalError); }

        public override string Name => "Date In Future Validator";

    }

}

Create the rule definition item in Sitecore



Add your rules to your fields


Test the validation


Updated the past date and try to save the page

No comments:

Post a Comment

Steps to follow when using a PowerShell script to modify the goals in Sitecore

I have previously utilized PowerShell for item creation, modification, deletion, and presentation details in Sitecore.   Ø Recently, I attem...