Regular Expression Model Validation in DevExpress

DevExpress provides model validation out of the box. Yes, really. We’re going to briefly cover two types of validation: making a field required, and validating a field against a regular expression.

First, making a field required. Simply add the required attribute to your model’s field, like so:


[RuleRequiredField("RuleRequiredField for Car.Year", DefaultContexts.Save)]
public int Year { get; set; }

This code has a few pieces to it; it has a string name (I diverged from the default to add the model name in there); and it activates on DefaultContexts.Save, which occurs when you click Save or Validate.

Great. Now, how do we validate that the year is between 19xx and 20xx? With a regular expression, of course!


[RuleRegularExpression("Regex for Car.Year", DefaultContexts.Save, "(19|20)\d{2}", "Enter a year between 1900 and 2099")]

Arguably, you could cover this with a range validator, but in any event, we’ll pretend that’s not the case. The constructor for this attribute takes an additional regex to validate against the field value.

And beware; the RuleRegularExpression alone does not guarantee non-nullness. Although the regular expression itself does not allow an empty value, an empty car year will sail through validation; so ensure that you have both attributes.

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Libraries, Web, Wndows Forms and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *