Skip to main content

Validation Attributes

  • 7 minutes to read

DevExtreme-based controls support several built-in ASP.NET Core attributes that reside in the System.ComponentModel.DataAnnotations namespace, along with other validation attributes:

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.

Attach validation attributes to model properties. Refer to Model Validation in ASP.NET Core for more information.

Model properties can have multiple attributes. The following code demonstrates the Person model that contains the FirstName property annotated with three validation attributes:

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; }
    }
}

The attributes are applied when you bind DevExtreme-based controls to model properties. Refer to Configure Controls to Validate for more information.

Range Attribute

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 demonstrates how to specify 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; }
    }
}    

Remote Attribute

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:

  1. Create a controller’s action method that checks if a specified e-mail is registered.

    [HttpPost]
    public IActionResult CheckEmailAddress(string email) {
        if(!_userRepository.VerifyEmail(email)) {
            return Json($"Email {email} is already registered.");
        }
    
        return Json(true);
    }
    
  2. In a model class, annotate the Email property with the [Remote] attribute, specify a controller’s action method, and a controller’s name.

    using System.ComponentModel.DataAnnotations;
    
    [Remote("CheckEmailAddress", "Validation")]
    public string Email { get; set; }
    
  3. Bind the TextBox editor to the Email property. Refer to Validate an Editor for more information.

    @model ApplicationName.Models.Person
    
    // ...
    
    @Html.DevExtreme().TextBoxFor(model => model.Email)
    

    Remote Attribute

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. In other words, 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 demonstrates how to use the AdditionalFields property.

Required Attribute

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.

DevExtremeRequired Attribute

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; }
    }
}    

DevExtremeRequired Attribute

Custom Attribute

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.

  1. 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.

    Implement the following methods:

    • IsValid

      Validates data on the server to ensure invalid values are not sent when JavaScript is switched off on the client.

    • AddValidation

      Adds the following attributes to the attribute dictionary. DevExtreme client-side validation engine uses these attributes.

      • data-val-custom-verifyage - Accepts a formatted validation message.

      • data-val-custom-verifyage-validationcallback - Specifies a JavaScript function that implements the validation logic.

      Note

      The attribute names should be in the following format: data-val-custom-yourattribute and data-val-custom-yourattribute-validationcallback .

    • FormatErrorMessage

      Overrides the default FormatErrorMessage method.

    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
    
    namespace DevExtreme.NETCore.Demos.ViewModels {
        public class VerifyAgeAttribute : ValidationAttribute, IClientModelValidator {
            public VerifyAgeAttribute(int age) {
                Age = age;
            }
            public int Age { get; private set; }
            protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
                if((DateTime?)value <= DateTime.Now.AddYears(-Age)) {
                    return ValidationResult.Success;
                }
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            }
            void IClientModelValidator.AddValidation(ClientModelValidationContext context) {
                context.Attributes.Add("data-val-custom-verifyage", FormatErrorMessage(context.ModelMetadata.GetDisplayName()));
                context.Attributes.Add(
                    "data-val-custom-verifyage-validationcallback",
                    $@"function(options) {{
                        var now = new Date();
                        return options.value && options.value <= now.setFullYear(now.getFullYear() - {Age});
                    }}");
            }
            public override string FormatErrorMessage(string name) {
                return string.Format(ErrorMessageString, name, Age);
            }
        }
    }
    
  2. Attach the VerifyAge attribute to a model property and specify an age.

    using System.ComponentModel.DataAnnotations;
    
    namespace ApplicationName.Models {
        public class Person {
            // ...
            [VerifyAge(21, ErrorMessage = "You must be at least {1} years old")]
            public DateTime? BirthDate { get; set; }
        }
    }
    
  3. Bind the DateBox control to the BirthDate model property. Refer to Validate an Editor for more information.

    @model ApplicationName.Models.Person
    
    // ...
    
    @(Html.DevExtreme().DateBoxFor(model => model.BirthDate))
    

    Custom Attribute

Note

Demo: You can find the provided code snippet in the Editors - Validation demo.