Validate Data
- 4 minutes to read
The DevExpress ASP.NET MVC GridView extension and DevExpress ASP.NET MVC Data Editors support a model-based data validation approach. According to this approach, you should use jQuery validation and decorate model class properties with the DataAnnotations attributes.
Note
Refer to the following topic to get more information about validation approaches: Supported Data Annotation Attributes
This topic illustrates how to validate data in the DevExpress ASP.NET MVC GridView extension.
- Add Validation Rules to the Model Class
- Enable Server-Side Validation
- Enable Unobtrusive Client Validation
- Display Validation Error Messages
Add validation rules to the model class
Add the required DataAnnotation attributes to the corresponding model class properties to specify validation rules for the model fields.
See also: How data annotations for ASP.NET MVC validation work.
using System.ComponentModel.DataAnnotations;
namespace Validation.Models {
public class Clients {
[Required(ErrorMessage = "First name is required")]
[StringLength(15, ErrorMessage = "Must be under 15 characters")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Email is required")]
[EmailAddress(ErrorMessage = "Email is invalid")]
public string Email { get; set; }
[Required(ErrorMessage = "Age is required")]
public int Age { get; set; }
}
}
Enable Server-Side Validation
When users submit data, the grid sends a callback to the server and calls an appropriate action method. In the action method, use the ModelStateDictionary.IsValid property to get the user input validation state. If the user input is valid, the grid adds/updates data to the data source. Otherwise, the grid displays an error message near the grid editor that contains invalid data.
Controller code:
// Handles grid callbacks to add a new record.
[HttpPost, ValidateInput(false)]
public ActionResult GridViewPartialAddNew(MyProject.Models.Customer item)
{
// Performs server-side model validation based on data annotation attributes.
if (ModelState.IsValid)
{
// Adds a new record to the data source.
}
else
ViewBag.EditError = "Please, correct all errors.";
// Returns the grid's Partial View with a data model object.
return PartialView("_GridViewPartial", GetData());
}
// Handles grid callbacks to update a record.
[HttpPost, ValidateInput(false)]
public ActionResult GridViewPartialUpdate(MyProject.Models.Customer item)
{
// Performs server-side model validation based on data annotation attributes.
if (ModelState.IsValid)
{
// Updates the record in the data source.
}
else
ViewBag.EditError = "Please, correct all errors.";
// Returns the grid's Partial View with a data model object.
return PartialView("_GridViewPartial", GetData());
}
Enable Unobtrusive Client Validation
Unobtrusive client validation allows you to validate model fields without sending a callback to the server.
Note
Include the jquery-3...min.js, jquery.validate.min.js and jquery.validate.unobtrusive.min.js JavaScript libraries in the order they are specified in the following code sample to enable the client-side validation.
Use the following code samples to include the required JavaScript references:
Applies the client-side validation to a single web page.
<script src="~/Scripts/jquery-3.5.1.min.js" type="text/javascript"></script> <script src="~/Scripts/jquery.validate.min.js" type="text/javascript"></script> <script src="~/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
Applies the client-side validation to all pages in a project (Web.Config file).
... <configuration> <appSettings> <add key="ClientValidationEnabled" value="true"/> <add key="UnobtrusiveJavaScriptEnabled" value="true"/> </appSettings> </configuration> ...
Applies the client-side validation to a specific view.
Partial View:
@{ Html.EnableClientValidation(); Html.EnableUnobtrusiveJavaScript(); }
View:
//Places the partial view inside the **form** tag. @using (Html.BeginForm()){ @Html.Action("GridViewPartial") }
Note
For the GridView, specify the IEnumerable<T> model as the GridView’s partial view model.
Display Validation Error Messages
For Server-Side Validation
The ASP.NET MVC GridView extension allows you to display error messages in the edit form or error row.
Use the MVCxGridViewEditingSettings.ShowModelErrorsForEditors property to specify whether the grid displays validation error messages for data editors in the edit form.
settings.SettingsEditing.ShowModelErrorsForEditors = true;
The grid displays an error message based on the ModelState object. Use the AddModelError method to specify custom error text for the required column in the Controller code.
public ActionResult Adding(Item model) {
ModelState.AddModelError("Text", "The Text property is always invalid during INSERTING");
return PartialView("GridPartial", new Model());
}
public ActionResult Editing(Item model) {
ModelState.AddModelError("Text", "The Text property is always invalid during EDITING");
return PartialView("GridPartial", new Model());
}
For Client-Side Validation
Use the DevExpress ASP.NET MVC Data Editors’ ShowModelErrors property to specify whether the grid displays error messages in editors when validation fails. The ValidationSettings.ErrorDisplayMode property specifies whether the error message contains an error text, icon and tooltip.
ErrorDisplayMode property value | Description | Image |
---|---|---|
ImageWithText | An error message includes text and an image. | |
ImageWithTooltip | An error message contains only an image. The image’s tooltip displays the error text. | |
Text | An error message contains only text. | |
None | The grid displays an error frame around an editor. |