Wednesday, October 28, 2015

Sitecore custom field validation rules

Out of the box there are a number of field validation rules which can be applied to template fields (for both item templates and rendering/sublayout parameters templates).
These rules are stored under /sitecore/system/Settings/Validation Rules/Field Rules.

As an example there is one to check for an email (Is Email), one to validate for integer/number (Is Integer) and even examples such as a minimum length of 8. They provide a good example base for creating custom rules.

Creating a custom field validation rule

An example validation rule is the case of a custom Google Maps sublayout. This sublayout has parameters to created the base configuration (width, height and default zoom level) - the locations can the be added as a datasource. In the example of Zoom, the Google Maps API allows for a level from 0 (entire world) to 19 (detailed street level), therefore the zoom field needs to be validated to ensure it's in the range of 0 to 19. To create this custom rule:
  1. Under /sitecore/system/Settings/Validation Rules/Field Rules click insert Validation Rule and call it Google Maps Zoom.
    1. Give it a Title of "Google Maps Zoom"
    2. Set the description to "The field must have a value between 0 and 19." - this is shown to the user.
    3. The type would be Sitecore.Data.Validators.FieldValidators.IntegerRangeValidator,Sitecore.Kernel which has been taken from one of the examples
    4. The parameters is set to Min=0&Max=19&Result=FatalError - see below for the result options
    5. Save the rule
  2. Navigate to the template where the validation needs to be applied and select the field name in the content tree.

  3. Under the Validation Rules section, select the Google Map Zoom rule for each of the four options: quick action bar, validate button, validator bar and workflow.

  4. Save the template, the validation rule is now active.
Now whenever the user attempts to save a value to Zoom outside of the range they will get a fatal validation error,

This is because of the Result element on the validation rule's parameters, there are a number of values that can be set here.
  • FatalError: Field is validated with an error, and the user can't save until the validation is fixed (red color)
  • CriticalError: Field is validated with an error, and the user gets a warning (red color)
  • Error: Field is validated with an error (red color)
  • Warning: Field is validated with a warning (orange color)
  • Suggestion: Field is validated with a suggestion (orange color)
  • Valid: Field is validated as acceptable (green color)

No comments:

Post a Comment