Your search did not match any results.

Validation

This demo shows how to implement a default validation group - a group of editors on a page with enabled data validation. In this particular demo, the editors are grouped in an HTML form.

Backend API
@model DevExtreme.NETCore.Demos.ViewModels.EditorsViewModel @using (Html.BeginForm()) { using (Html.DevExtreme().ValidationGroup()) { @Html.AntiForgeryToken() <div class="dx-fieldset"> <div class="dx-fieldset-header">Credentials</div> <div class="dx-field"> <div class="dx-field-label"> @Html.LabelFor(m => m.Email) </div> <div class="dx-field-value"> @Html.DevExtreme().TextBoxFor(m => m.Email) </div> </div> <div class="dx-field"> <div class="dx-field-label"> @Html.LabelFor(m => m.Password) </div> <div class="dx-field-value"> @(Html.DevExtreme().TextBoxFor(m => m.Password) .Mode(TextBoxMode.Password) .ID("Password") .OnValueChanged("onPasswordChanged") .Buttons(buttons => { buttons.Add() .Name("password") .Location(TextEditorButtonLocation.After) .Widget(w => w.Button() .StylingMode(ButtonStylingMode.Text) .Icon("eyeopen") .OnClick("() => changePasswordMode('Password')")); }) ) </div> </div> <div class="dx-field"> <div class="dx-field-label"> @Html.LabelFor(m => m.ConfirmPassword, "Confirm Password") </div> <div class="dx-field-value"> @(Html.DevExtreme().TextBoxFor(m => m.ConfirmPassword) .Mode(TextBoxMode.Password) .ID("ConfirmPassword") .Buttons(buttons => { buttons.Add() .Name("password") .Location(TextEditorButtonLocation.After) .Widget(w => w.Button() .StylingMode(ButtonStylingMode.Text) .Icon("eyeopen") .OnClick("() => changePasswordMode('ConfirmPassword')")); }) ) </div> </div> </div> <div class="dx-fieldset"> <div class="dx-fieldset-header">Personal Data</div> <div class="dx-field"> <div class="dx-field-label"> @Html.LabelFor(m => m.Name) </div> <div class="dx-field-value"> @Html.DevExtreme().TextBoxFor(m => m.Name) </div> </div> <div class="dx-field"> <div class="dx-field-label"> @Html.LabelFor(m => m.Date, "Date of birth") </div> <div class="dx-field-value"> @(Html.DevExtreme().DateBoxFor(m => m.Date) .InvalidDateMessage("The date must have the following format: MM/dd/yyyy") ) </div> </div> <div class="dx-field"> <div class="dx-field-label"> @Html.LabelFor(m => m.VacationDates, "Vacation Dates") </div> <div class="dx-field-value"> @(Html.DevExtreme().DateRangeBoxFor(m => m.VacationDates) .ID("DateRangeBox") .OnValueChanged("onVacationDatesChange") ) </div> </div> </div> <div class="dx-fieldset"> <div class="dx-fieldset-header">Billing address</div> <div class="dx-field"> <div class="dx-field-label"> @Html.LabelFor(m => m.Country) </div> <div class="dx-field-value"> @(Html.DevExtreme().SelectBoxFor(m => m.Country) .DataSource(d => d.Mvc().Controller("GeoNames").LoadAction("Countries").Key("this")) .ValidationMessagePosition(Position.Left) ) </div> </div> <div class="dx-field"> <div class="dx-field-label"> @Html.LabelFor(m => m.City) </div> <div class="dx-field-value"> @(Html.DevExtreme().TextBoxFor(m => m.City) .ValidationMessagePosition(Position.Left) ) </div> </div> <div class="dx-field"> <div class="dx-field-label"> @Html.LabelFor(m => m.Address) </div> <div class="dx-field-value"> @(Html.DevExtreme().TextBoxFor(m => m.Address) .ValidationMessagePosition(Position.Left) ) </div> </div> <div class="dx-field"> <div class="dx-field-label"> @Html.LabelFor(m => m.Phone) <i>(optional)</i> </div> <div class="dx-field-value"> @(Html.DevExtreme().TextBoxFor(m => m.Phone) .Mask("+1 (X00) 000-0000") .MaskRules(new { X = new JS("/[02-9]/") }) .MaskInvalidMessage("The phone must have a correct USA phone format") .ValidationMessagePosition(Position.Left) ) </div> </div> </div> <div class="dx-fieldset"> <div class="dx-field"> <div class="dx-field-label"> @(Html.DevExtreme().CheckBoxFor(m => m.Accepted) .ID("check") .Text("I agree to the Terms and Conditions") .ValidationMessagePosition(Position.Right) ) </div> <div class="dx-field-value"> @(Html.DevExtreme().Button() .Width("120px") .Text("Register") .Type(ButtonType.Default) .UseSubmitBehavior(true) ) </div> </div> @(Html.DevExtreme().ValidationSummary() .ID("summary") ) </div> } } <script> function changePasswordMode(name) { let editor = $(`#${name}`).dxTextBox("instance"); editor.option('mode', editor.option('mode') === 'text' ? 'password' : 'text'); } function onPasswordChanged(e) { let editor = $("#ConfirmPassword").dxTextBox("instance"); if (editor.option("value")) { editor.element().dxValidator("validate") } } function onVacationDatesChange(e) { const editor = $("#DateRangeBox").dxDateRangeBox("instance"); const [startDate, endDate] = editor.option("value"); let isValid; if (startDate === null && endDate === null) { isValid = true; } else { isValid = startDate !== null && endDate !== null; } if (!isValid) { editor.option({ validationStatus: "invalid", validationErrors: [{ message: "Both start and end dates must be selected" }] }); } } </script>
<p>The submitted data has been successfully accepted.</p> <br /> @(Html.DevExtreme().Button() .Text("Reload demo") .Type(ButtonType.Default) .Icon("refresh") .OnClick(@<text> function() { window.location = window.location; } </text>) )
using System; using System.Linq; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Memory; using DevExtreme.NETCore.Demos.Models.DataGrid; namespace DevExtreme.NETCore.Demos.Controllers { public class RemoteValidationController : Controller { InMemoryEmployeesValidationDataContext _db; public RemoteValidationController(IHttpContextAccessor httpContextAccessor, IMemoryCache memoryCache) { _db = new InMemoryEmployeesValidationDataContext(httpContextAccessor, memoryCache); } [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); } [HttpPost] public JsonResult CheckEmailAddress(string email) { var isValid = !string.Equals(email, "test@dx-email.com", StringComparison.OrdinalIgnoreCase); return Json(isValid); } } }
using DevExtreme.NETCore.Demos.ViewModels; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; namespace DevExtreme.NETCore.Demos.Controllers { public class ValidationController : Controller { [HttpGet] public ActionResult Overview() { return View(new EditorsViewModel { Name = "Peter", VacationDates = new DateTime?[] { null, null } }); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Overview(EditorsViewModel userInfo) { if(ModelState.IsValid) { return View("SuccessValidation"); } return View(userInfo); } [HttpPost] public JsonResult CheckEmailAddress(string email) { bool isValid = string.Equals(email, "test@test.com", StringComparison.OrdinalIgnoreCase); return Json(isValid); } } }
using DevExtreme.AspNet.Data; using DevExtreme.AspNet.Mvc; using DevExtreme.NETCore.Demos.Models.SampleData; using Microsoft.AspNetCore.Mvc; using System; using System.Linq; using System.Net.Http; namespace DevExtreme.NETCore.Demos.Controllers.ApiControllers { [Route("api/[controller]/[action]")] public class GeoNamesController : Controller { [HttpGet] public object Countries(DataSourceLoadOptions loadOptions) { return DataSourceLoader.Load(SampleData.Countries, loadOptions); } [HttpGet] public object Cities(DataSourceLoadOptions loadOptions) { return DataSourceLoader.Load(SampleData.Cities, loadOptions); } } }
using DevExtreme.AspNet.Mvc; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace DevExtreme.NETCore.Demos.ViewModels { public class EditorsViewModel { [Required(ErrorMessage = "Email is required")] [RegularExpression(@"^[\d\w._-]+@[\d\w._-]+\.[\w]+$", ErrorMessage = "Email is invalid")] [Remote("CheckEmailAddress", "RemoteValidation", ErrorMessage = "Email is already registered", HttpMethod = "POST")] public string Email { get; set; } = string.Empty; [Required(ErrorMessage = "Name is required")] [RegularExpression(@"^[^0-9]+$", ErrorMessage = "Do not use digits in the Name.")] [StringLength(int.MaxValue, MinimumLength = 2, ErrorMessage = "Name must have at least 2 symbols")] public string Name { get; set; } = string.Empty; [Required(ErrorMessage = "Password is required")] public string Password { get; set; } = string.Empty; [Required(ErrorMessage = "Confirm Password is required")] [System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "'Password' and 'Confirm Password' do not match.")] public string ConfirmPassword { get; set; } = string.Empty; [RegularExpression(@"^[02-9]\d{9}$", ErrorMessage = "The phone must have a correct USA phone format")] public string Phone { get; set; } = string.Empty; public string Extension { get; set; } [Required(ErrorMessage = "Country is required")] public string Country { get; set; } [Required(ErrorMessage = "Address is required")] public string Address { get; set; } = string.Empty; public string Description { get; set; } public int Age { get; set; } public string Drink { get; set; } [Required(ErrorMessage = "City is required")] [RegularExpression("^[^0-9]+$", ErrorMessage = "Do not use digits in the City name.")] [StringLength(int.MaxValue, MinimumLength = 2, ErrorMessage = "City must have at least 2 symbols")] public string City { get; set; } public IEnumerable<string> Colors { get; set; } public IEnumerable<string> SelectedColors { get; set; } public string Color { get; set; } [Display(Name = "Date of birth")] [Required(ErrorMessage = "Date of birth is required")] [VerifyAge(21, ErrorMessage = "You must be at least {1} years old")] public DateTime? Date { get; set; } [VerifyDateRange(25, ErrorMessage = "The vacation period must not exceed {1} days")] public DateTime?[] VacationDates { get; set; } [DevExtremeRequired(ErrorMessage = "You must agree to the Terms and Conditions")] public bool Accepted { get; set; } } }
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; 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); } } }
#summary { padding-left: 10px; margin-top: 20px; margin-bottom: 10px; }

To enable data validation for an editor, you need to declare the Validator component and implement validation rules. You can attach multiple validation rules to one component. The following list contains all available validation rule types:

  • required
    A validation rule that requires the validated field to have a value.

  • email
    A validation rule that requires the validated field to match the Email pattern.

  • async
    A custom validation rule used for server-side validation. Implement the validationCallback function to validate the target value.

  • compare
    A validation rule that requires the validated editor's value to equal the value of the specified expression. To apply this rule, implement the comparisonTarget function to specify the value against which this component compares the validated value.

  • pattern
    A validation rule that requires the validated field to match a specified pattern.

  • stringLength
    A validation rule that requires the target value length to fall within the range of the specified minimum and maximum values. This property only accepts string values.

  • range
    A validation rule that requires the target value length to fall within the range of the specified minimum and maximum values. This property only accepts date-time and numeric values.

  • numeric
    A validation rule that requires the validated field to have a numeric value.

  • custom
    A rule with custom validation logic. Implement the validationCallback function to validate the target value.

All validation rule types allow you to specify an error message for a component. You can also specify the message position for each editor. If your application implements a validation group, you can use a validation summary to display all validation errors in one place. In this demo, click the Register button to see a validation summary.

The Register button's useSubmitBehavior property is enabled. As a result, a click on the button validates and submits the HTML form. In your application, you can also implement the button's onClick event handler and use the validate() or validateGroup() method to validate a group of editors.