After my previous post about comparing Comparing PageTypeBuilder and EPiServer 7 Preview typed pages I found out that EPiServer 7 Preview now also supports standard .net validation attributes too.

I am sure you have had requirements that users can only enter numbers that are between 1 and 10, strings that are only 10 characters long or postcodes. In previous versions these all required custom properties but now these are all covered by using the System.ComponentModel.DataAnnotations.RegularExpression, System.ComponentModel.DataAnnotations.Range and System.ComponentModel.DataAnnotations.StringLength attributes.

I wanted to put a few examples together to demonstrate the usage of the attributes and their effect in the UI.

Range attribute usage

This allows us to specify a range for numbers. The code is super simple:

[Display(
    Name = "RangeAttribute",
    Description = "RangeAttribute.",
    GroupName = "Validation tests",
    Order = 99)]
[Range(0, 10)]
public virtual int RangeAttribute { get; set; }

This has the following effect in the UI:

Range Validator in EPiServer 7

StringLength attribute usage

This is simple but powerful and restricts users from entering more than a defined number of characters in a string:

[Display(
        Name = "StringLenghAttribute",
        Description = "StringLenghAttribute.",
        GroupName = "Validation tests",
        Order = 101)]
[StringLength(20)]
public virtual string StringLenghAttribute { get; set; }

As seen in the UI (this uses HTML maxlength attribute to restrict the length):

StringLength Validator in EPiServer 7

RegularExpression validation attribute

This as you can guess uses a regular expreessoin to validate the input. This is all done client side which is a nice touch and a real advance on previous versions of EPiServer. The example below is for a UK post code:

[Display(
        Name = "PostCodeRegexAttribute",
        Description = "RegexAttribute.",
        GroupName = "Validation tests",
        Order = 101)]
[RegularExpression("^(([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2}))$"
    , ErrorMessage = "Must be valid UK postcode")]
public virtual string PostCodeRegexAttribute { get; set; }

As seen in the UI (this uses HTML maxlength attribute to restrict the length):

RegularExpression Validator in EPiServer 7

Error summary

The UI also presents an error summary which is a nice touch:

Error Summary in EPiServer 7

Conclusion

This is an example of EPiServer trying to adopt standard .net framework validation attributes which is a nice implementation and lowers the barrier to entry for new EPiServer developers.

Feedback

I'd be happy to hear any feedback on the comments below or @davidknipe


Comments

Recommendations for you