Chapter 11 Slides
Chapter 11 Slides
How to
validate data
Knowledge
2. Describe the default data validation provided by model binding.
3. Describe the use of attributes for data validation.
4. List six data validation attributes.
5. Describe the use of tag helpers for data validation.
6. Describe the use of the IsValid property of a controller’s
ModelState property.
7. Describe the use of CSS to format validation messages.
[Range(1, 5)]
public int Rating { get; set; }
}
[Range(1, 5,
ErrorMessage = "Please enter a rating between 1 and 5.")]
public int Rating { get; set; }
if (ModelState.GetValidationState(key) ==
ModelValidationState.Valid) {
if (customer.DOB > DateTime.Today) {
ModelState.AddModelError(
key, "Date of birth must not be a future date.");
}
}
if (ModelState.IsValid) {
// code that adds customer to database
return RedirectToAction("Welcome");
}
else {
return View(customer);
}
}
if (IsPast) {
from = new DateTime(now.Year, 1, 1);
from = from.AddYears(-numYears);
}
// check date
if (IsPast) {
if (dateToCheck >= from && dateToCheck < now) {
return ValidationResult.Success;
}
}
else {
if (dateToCheck > now && dateToCheck <= from) {
return ValidationResult.Success;
}
}
}
string msg = base.ErrorMessage ??
ctx.DisplayName + " must be a " +
(IsPast ? "past" : "future") + " date within " +
numYears + " years of now.";
return new ValidationResult(msg);
}
}
jQuery.validator.unobtrusive.adapters.addSingleVal(
"pastdate", "numyears");
<script src="~/lib/jquery/jquery.min.js"></script>
<script src="~/lib/jquery-validation/jquery.validate.min.js">
</script>
<script src="~/lib/jquery-validation-unobtrusive/
jquery.validate.unobtrusive.min.js"></script>
<script src="~/js/pastdate.js"></script>
<title>@ViewBag.Title</title>
</head>
The view
<input asp-for="EmailAddress" class="form-control" />
<input asp-for="Username" class="form-control" />
<input type="hidden" name="Region" value="West" />
dateToCheck.setFullYear(dateToCheck.getFullYear() +
minYears);
jQuery.validator.unobtrusive.adapters.addSingleVal(
"minimumage", "years");
[HttpPost]
public IActionResult Index(Customer customer)
{
if (TempData["okEmail"] == null) {
string msg = Check.EmailExists(
context, customer.EmailAddress);
if (!String.IsNullOrEmpty(msg)) {
ModelState.AddModelError(
nameof(Customer.EmailAddress), msg);
}
}
@{
ViewData["Title"] = "Registration";
}
@section scripts {
<script
src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/
jquery.validate.unobtrusive.min.js"></script>
<script src="~/js/minimum-age.js"></script>
}