Entity validation
With the API, 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:
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'
}
}
How to work with MultiField
When executing result.AddError(), the first param, a string param named key, is the Id of the field we are validating. In the example above, it is Specification. This Id is used by the system's User interface(UI) in order to find the field in the UI and show error message.
In case of MultiField, where a field contains many fields, the Id is built by the MultiField's Id, the Id of the field item and its index(starts from 1). For example, in Website, we have a MultiField called Footer and it has a text field called FooterHeader. Below is a sample code to show an error message for the first FooterHeader field:
namespace Litium.Accelerator.Validations.EntityValidations
{
public class SampleValidation : ValidationRuleBase<Website>
{
public override ValidationResult Validate(Website entity, ValidationMode validationMode)
{
var result = new ValidationResult();
result.AddError("Footer|FooterHeader|1", "Something went wrong!");
return result;
}
}
}