aspnetcore-401551-devextreme-based-controls-concepts-data-validation-validation-attributes.md
DevExtreme-based controls support multiple validation attributes, including built-in ASP.NET Core attributes (included in System.ComponentModel.DataAnnotations):
| Attribute | Description | Remarks |
|---|---|---|
| Compare | Validates that two property values in a model match. | Built-in |
| Range | Validates that a property value falls within a specified range. | Built-in |
| RegularExpression | Validates that a property value matches a specified regular expression. | Built-in |
| Remote | Performs a remote validation when you call an action method on the server to validate inputs on the client. | Built-in |
| Required | Validates that an editor’s value is not null. | Built-in |
| StringLength | Validates that a string property value does not exceed a specified length limit. | Built-in |
| DevExtremeRequired | Validates that a Boolean property value is true. | DevExtreme-specific |
| A custom attribute | You can create a custom validation attribute. |
To use validation attributes, attach these attributes to model properties. For more information, refer to the following topic: Model Validation in ASP.NET Core.
You can attach multiple attributes to model properties. The following code attaches three validation attributes to the FirstName property:
using System.ComponentModel.DataAnnotations;
namespace ApplicationName.Models {
public class Person {
[Required(ErrorMessage = "First name is required")]
[RegularExpression(@"^[a-zA-Z\s]+$", ErrorMessage = "Please, use letters in the first name. Digits are not allowed.")]
[StringLength(int.MaxValue, MinimumLength = 2, ErrorMessage = "First name must have at least 2 characters")]
public string FirstName { get; set; }
}
}
Attributes are applied when you bind DevExtreme-based controls to model properties. For more information, refer to the following topic: Configure Controls to Validate.
Note
You cannot use client-side localization API (such as the locale() method) to translate validation attribute messages. Configure ErrorMessage to specify one translation. To implement multiple translations, refer to the following guide: Globalization and localization in ASP.NET Core.
The Range attribute allows you to specify minimum and maximum values for a model property.
If the Range attribute should limit a date or time range, use the attribute overload that accepts a type as the first argument. The date/time values should be strings.
The following code sample specifies a range for the BirthDate model property:
using System.ComponentModel.DataAnnotations;
namespace ApplicationName.Models {
public class Person {
// ...
[Range(typeof(DateTime), "1/1/1901", "1/1/2016")]
public DateTime BirthDate { get; set; }
}
}
The Remote attribute allows you to perform remote data validation. You can call an action method on the server to validate inputs on the client.
For example, you can add remote validation for an e-mail input:
Create a controller’s action method that checks if a specified e-mail is registered.
In a model class, annotate the Email property with the [Remote] attribute, specify a controller’s action method, and a controller’s name.
Bind the TextBox editor to the Email property. Refer to Validate an Editor for more information.
Refer to RemoteAttribute Class for more information.
Note
The Editors - Validation and Form - Validation online demos demonstrate how to use the [Remote] attribute.
The AdditionalFields property of the Remote attribute allows you validate combinations of fields against data on the server. DevExtreme DataGrid and TreeList support this property.
For instance, if a user entered an email and it is already in the database, you may need to check whether you need to create a new profile or edit an existing one. You need to check whether a new ID is about to be associated with an existing Email. To accomplish that, apply a Remote attribute to Email and include ID in AdditionalFields. The validation method’s parameter will then have access to ID in addition to Email, so you can compare both values to source data.
@(Html.DevExtreme().DataGrid<EmployeeValidation>()
.Editing(editing => {
editing.AllowUpdating(true);
editing.AllowAdding(true);
})
.Columns(columns => {
columns.AddFor(m => m.ID);
columns.AddFor(m => m.Email);
})
)
using System.ComponentModel.DataAnnotations;
public class EmployeeValidation {
public int ID { get; set; }
[Remote("CheckUniqueEmailAddress", "RemoteValidation", AdditionalFields = nameof(ID))]
public string Email { get; set; }
}
[HttpPost]
public JsonResult CheckUniqueEmailAddress(EmployeeValidation model) {
var isValid = !db.Employees.Any(emp => {
var equals = string.Equals(emp.Email, model.Email, StringComparison.OrdinalIgnoreCase);
return model.ID != emp.ID && equals;
});
return Json(isValid);
}
Note
The DataGrid - Data Validation online demo uses the AdditionalFields property.
The Required attribute allows you to validate that an editor’s value is not null.
If you bind controls to non-nullable properties, you can receive the The value ‘’ is invalid error message. Refer to Microsoft Documentation: Required Validation on the Server for more information.
The DevExtremeRequired attribute resides in the DevExtreme.AspNet.Mvc namespace and allows you to verify if a Boolean value is true. Refer to this blog post for more information on why you should use this attribute instead of the built-in Required attribute.
For example, you can use this attribute for the CheckBox control when you need to check if the control’s value is true (CheckBox is selected).
@using(Html.BeginForm("EditPerson", "Home", FormMethod.Post, new { id = "editPerson" })) {
@(Html.DevExtreme().Form<Person>()
.Items(items => {
// ...
items.AddSimpleFor(model => model.Accepted)
.Label(label => label.Visible(false))
.Editor(editor => editor.CheckBox().Text("I agree to the Terms and Conditions"));
})
)
}
using DevExtreme.AspNet.Mvc;
using System.ComponentModel.DataAnnotations;
namespace ApplicationName.Models {
public class Person {
// ...
[DevExtremeRequired(ErrorMessage = "You must agree to the Terms and Conditions")]
public bool Accepted { get; set; }
}
}
You can implement a custom attribute if built-in ASP.NET Core validation attributes do not meet your requirements.
The steps below describe how to create the VerifyAge attribute and apply it to the DateBox control. The attribute should check if a person is over the specified age, for example, the age of 21.
Create the VerifyAgeAttribute class that implements the validation logic. Duplicate this logic on the client and on the server. To do this, declare the class that is inherited from the ValidationAttribute class and implements the IClientModelValidator interface.
Attach the VerifyAge attribute to a model property and specify an age.
Bind the DateBox control to the BirthDate model property. Refer to Validate an Editor for more information.
Note
Demo: You can find the provided code snippet in the Editors - Validation demo.