If you have a requirement to validate the content in the Sitecore field then out of the box Sitecore provides few validations that can be applied in the field "Validation Bar" of Field Item.
But, if there is a custom validation requirement to validate the content then we can create custom validation as well.
For demo purposes, we will validate that the field should not contain the '&' symbol.
Use the following steps to create the custom validation.
- Create a custom validator class inheriting it from Sitecore.Data.Validators.StandardValidator
using Sitecore.Data.Fields; using Sitecore.Data.Validators; using System.Runtime.Serialization; namespace BasicCompany.Feature.POC.Extension.FieldValidator { public class AmpersandValidator : StandardValidator { public AmpersandValidator() : base() { } public AmpersandValidator(SerializationInfo info, StreamingContext context) : base(info, context) { } protected override ValidatorResult Evaluate() { Field field = GetField(); if (field.Value.Contains("&")) { Text = GetText($"The field {field.DisplayName} can't contain symbol '&'."); return GetFailedResult(ValidatorResult.CriticalError); } return ValidatorResult.Valid; } protected override ValidatorResult GetMaxValidatorResult() { return ValidatorResult.Error; } public override string Name { get { return "AmpersandValidator"; } } } }
- Create Sitecore field validator item
- Create Sitecore field validator item "/sitecore/system/Settings/Validation Rules/Field Rules/" ( I have created Remove Ampersand item)
- Enter the appropriate values, as I have highlighted but be sure you provide the correct reference of your class and assembly in the "Type" field. This is the namespace where class "AmpersandValidator" is created and assembly name.
- Apply the custom field validator on the field item in the "Validation Bar" field
- Now check the validation on item:
- This will not let you save the item because in the "Title" field because '&' is present and the message for this error will be shown in the right-hand side in the bar when you hover the red dots.
Have any doubt?
Email: prashant.tomar@hotmail.com
https://sitecorepeanuts.blogspot.com/2020/08/custom-sitecore-field-validation.html
ReplyDelete