Model Validation
In addition to model constraints, you can also provide model validation via column validation attributes or custom validator.
Built-in attributes
Here are some of the built-in column validation attributes:
- CreditCard: Validates that the column has a credit card format.
- EmailAddress: Validates that the column has an email format.
- Phone: Validates that the column has a telephone number format.
- RegularExpression: Validates that the column value matches a specified regular expression.
- Required: Validates that the field is not null.
- StringLength: Validates that a string column value doesn't exceed a specified length limit.
- Url: Validates that the column has a URL format.
Error messages
Column validation attributes let you specify the error message to be displayed for invalid input. For example:
Internally, the attributes call String.Format with a placeholder for the column name and sometimes additional placeholders. For example:
When applied to a Name property, the error message created by the preceding code would be "Name length must be between 6 and 8.".
To find out which parameters are passed to String.Format for a particular attribute's error message, see the source code.
Custom attributes
For scenarios that the built-in column validation attributes don't handle, you can create custom validation attributes:
- Create a class that inherits from ValidationColumnAttribute;
- Override the
IsValid
method andDefaultMessageString
property; - Make sure your custom attribute is correctly decorated with ModelDesignerSpec to be friendly to Model Visualizer.
See the source code of built-in column validation attributes as examples.
Custom validator
Another option for model validation is to implement custom validator with property returns CustomValidatorEntry and a pair of CustomValidatorAttribute and _CustomValidatorAttribute in the model class, as shown in the following example:
[CustomValidator(nameof(VAL_ProductNumber))]
public class SalesOrderInfoDetail : ...
{
...
[_CustomValidator]
private CustomValidatorEntry VAL_ProductNumber
{
get
{
string Validate(DataRow dataRow)
{
if (ProductID[dataRow] == null)
return null;
var productNumber = Product.ProductNumber;
if (string.IsNullOrEmpty(productNumber[dataRow]))
return string.Format(UserMessages.Validation_ValueIsRequired, productNumber.DisplayName);
else
return null;
}
IColumns GetSourceColumns()
{
return Product.ProductNumber;
}
return new CustomValidatorEntry(Validate, GetSourceColumns);
}
}
...
}
You can add custom validator by clicking the left top drop down button of Model Visualizer tool window, then click 'Add Custom Validator...':
The following dialog will be displayed:
Fill the dialog form and click "OK", code of a to-be-implemented custom validator will be generated automatically.