Validation Attributes
- 7 minutes to read
DevExtreme ASP.NET MVC controls support several validation attributes that reside in the System.ComponentModel.DataAnnotations namespace and other validation attributes:
Attribute | Description | Remarks |
---|---|---|
Compare | Validates that two properties 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: you call an action method on the server to validate inputs on the client. | Built-in |
Required | Validates that a field 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 Adding Validation in ASP.NET MVC 5 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 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 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:
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.@model ApplicationName.Models.Person // ... @Html.DevExtreme().TextBoxFor(model => model.Email)
Refer to RemoteAttribute Class for more information.
Note
The Editors - Validation and Form - Validation online demos demonstrate how to use the [Remote]
attribute.
Required Attribute
The Required attribute allows you to validate that a field 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 is selected (its value is true
).
View
@using(Html.BeginForm("EditPerson", "Home", FormMethod.Post)) {
@(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"));
})
)
}
Model
using System.ComponentModel.DataAnnotations;
using DevExtreme.AspNet.Mvc;
namespace ApplicationName.Models {
public class Person {
// ...
[DevExtremeRequired(ErrorMessage = "You must agree to the Terms and Conditions")]
public bool Accepted { get; set; }
}
}
Custom Attribute
You can implement a custom attribute if built-in 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 the logic on the client and on the server. To do this, declare the class that is inherited from the ValidationAttribute class and implements the IClientValidatable 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.
GetClientValidationRules
Adds a validation rule used by DevExtreme client-side validation engine. The rule has the following properties:
ErrorMessage
- Accepts a formatted validation message.ValidationParameters
- Provides access to rule parameters. Use theAdd
method to add thevalidationcallback
parameter. The parameter should specify a JavaScript function that implements the validation logic.
FormatErrorMessage
Overrides the default FormatErrorMessage method.
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace DevExtreme.MVC.Demos.ViewModels { public class VerifyAgeAttribute : ValidationAttribute, IClientValidatable { 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)); } IEnumerable<ModelClientValidationRule> IClientValidatable.GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule(); rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()); rule.ValidationParameters.Add( "validationcallback", $@"function(options) {{ var now = new Date(); return options.value && options.value <= now.setFullYear(now.getFullYear() - {Age}); }}"); rule.ValidationType = "custom"; yield return rule; } public override string FormatErrorMessage(string name) { return string.Format(ErrorMessageString, name, Age); } } }
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.@model ApplicationName.Models.Person @(Html.DevExtreme().DateBoxFor(model => model.BirthDate))
Note
Demo: You can find the provided code in the Editors - Validation demo.