Validation

Entity validation

With the new API introduced in Litium 5, and that is being extended in Litium 6, it is possible to validate entity modifications by inheriting the abstract class ValidationRuleBase.

The example validation below is triggered on every modification of a BaseProduct entity.

using Litium.Products;
using Litium.Validations;

namespace Litium.Accelerator.Validations.EntityValidations
{
    public class ProductSpecificationLength : ValidationRuleBase<BaseProduct>
    {
        public override ValidationResult Validate(BaseProduct entity, ValidationMode validationMode)
        {
            var result = new ValidationResult();

            foreach (var localization in entity.Localizations)
            {
                var specification = entity.Fields.GetValue<string>("Specification", localization.Key);
                var specificationIsTooLong = !string.IsNullOrEmpty(specification) && specification.Length > 50;

                if (specificationIsTooLong)
                {
                    // Add an error message to the ValidationResult to fail validation
                    // First parameter defines where the errormessage should be displayed on edit-page,
                    // in this case the message will display next to the specification field.
                    result.AddError("Specification", "Specification can only be 50 characters long");
                }
            }

            return result;
        }
    }
}

On save:

EntityValidationBO.PNG 

Catch as ValidationException when updating entities in code. Example:

private void SaveBaseProduct(string longText)
{
    var baseProduct = _baseProductService.Get("636488389283921171-0001");
    var writeableBaseProduct = baseProduct.MakeWritableClone();
    writeableBaseProduct.Fields.AddOrUpdateValue("Specification", CultureInfo.CurrentCulture, longText);

    try
    {
        _baseProductService.Update(writeableBaseProduct);
    }
    catch (Litium.Validations.ValidationException e)
    {
        // e.Message:
        // Validation error for BaseProduct(SystemId: d450ff6f-95a3-4965-bb4b-f8f9510c53f4, Id: 636488389283921171-0001), 
        // Specification: 'Specification can only be 50 characters long'
    }
}

 

Is this page helpful?
Thank you for your feedback!