Overview - ASP.NET Core Validation Demo (2024)

@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.Mvc;using DevExtreme.NETCore.Demos.Models.DataGrid;using Microsoft.AspNetCore.Http;using Microsoft.Extensions.Caching.Memory;using Newtonsoft.Json.Linq;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([FromBody] JObject data) { int? id = (int?)data["id"]; string email = data["email"].ToString(); bool isValid = !_db.Employees.Any(emp => { bool isEqual = string.Equals(emp.Email, email, StringComparison.OrdinalIgnoreCase); return id != null ? id != emp.ID && isEqual : isEqual; }); return Json(isValid); } [HttpPost] public JsonResult CheckEmailAddress(string email) { bool isInvalid = string.Equals(email, "test@dx-email.com", StringComparison.OrdinalIgnoreCase); return Json(!isInvalid); } }}

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

Overview - ASP.NET Core Validation Demo (2024)
Top Articles
Latest Posts
Article information

Author: Chrissy Homenick

Last Updated:

Views: 5577

Rating: 4.3 / 5 (54 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Chrissy Homenick

Birthday: 2001-10-22

Address: 611 Kuhn Oval, Feltonbury, NY 02783-3818

Phone: +96619177651654

Job: Mining Representative

Hobby: amateur radio, Sculling, Knife making, Gardening, Watching movies, Gunsmithing, Video gaming

Introduction: My name is Chrissy Homenick, I am a tender, funny, determined, tender, glorious, fancy, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.