Home > Enterprise >  How do I validate forms properly in asp.NET MVC?
How do I validate forms properly in asp.NET MVC?

Time:09-12

I'm trying to validate my form but it just wont show up or be enforced for some reason?

I fill in the info and it will give me the info if I fill in the stuff so I know my post goes through. it just wont enforce any requirements. Viewmodel tied to the form:

using System.ComponentModel.DataAnnotations;
namespace PastaShop.Models
{
    public class PersoonViewModel:IValidatableObject
    {
        [Display(Name ="Naam")]
        [Required(ErrorMessage = "je moet een naam ingeven !")]
        public string? Naam { get; set; }

        [Display(Name = "Voornaam")]
        [Required(ErrorMessage = "je moet een voornaam ingeven !")]
        public string? Voornaam { get; set; }
        [Display(Name = "Email")]
        [Required(ErrorMessage ="je moet een Email ingeven !")]
        [EmailAddress]
        public string? Email { get; set; }
        [Display(Name = "Telefoon")]
        [Required(ErrorMessage = "je moet een Email ingeven !")]
        public string? Telefoon { get; set; }
        [Display(Name = "Geboortedatum")]
        [Required(ErrorMessage = "je moet een datum ingeven !")]
        public DateTime Geboortedatum { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var validationResults = new List<ValidationResult>();
            if (DateTime.Compare(Geboortedatum, DateTime.Now) > 0)
            {
                validationResults.Add(new ValidationResult("GeboorteDatum is in de toekomst !"));
                
            }
            return validationResults;
        }
    }
}

cshtml page tied to the form:

@{
    ViewData["Title"] = "Nieuwsbrief";
}

<h1>Nieuwsbrief</h1>

@model PersoonViewModel
@{
    ViewBag.Title = "Nieuwsbrief";
}
<div id="niewsbriefForm">
    <form asp-action="bevestigNieuwsBrief" method="post">
        <label asp-for="Naam"></label>
        <input type="text" asp-for="Naam" />
        <span asp-validation-for="Naam"></span>
        <br />
        <label asp-for="Voornaam"></label>
        <input type="text" asp-for="Voornaam" />
        <span asp-validation-for="Voornaam"></span>
        <label asp-for="Email"></label>
        <input type="email" asp-for="Email" />
        <span asp-validation-for="Email"></span>
        <label asp-for="Telefoon"></label>
        <input type="text" asp-for="Telefoon" />
        <span asp-validation-for="Telefoon"></span>
        <label asp-for="Geboortedatum"></label>
        <input type="text" asp-for="Geboortedatum" />
        <span asp-validation-for="Geboortedatum"></span>
        <input type="submit" value="Bevestigen"  />
        <div asp-validation-summary="All">Er zijn Validatiefouten! </div>
    </form>

</div>

actions in the homecontroller :

public IActionResult Nieuwsbrief()
        {
            var nieuwsbriefViewModel = new PersoonViewModel();
            return View(nieuwsbriefViewModel);

        }
        [HttpPost]
        public IActionResult BevestigNieuwsBrief(PersoonViewModel persoonViewModel)
        {
            if (this.ModelState.IsValid)
            {
                var persoon = new Persoon();
                persoon.Email = persoonViewModel.Email;
                persoon.Naam = persoonViewModel.Voornaam;
                return View(persoon);
            } else
            {
                return RedirectToAction(nameof(Nieuwsbrief));
            }


        }

Any help would be greatly appreciated !

CodePudding user response:

It could be that the validation JavaScript is not being loaded. Check that your "_Layout.cshtml" has a line like this:

@await Html.PartialAsync("_ValidationScriptsPartial")

For a project of mine, this is just above the @RenderSection("Scripts, false) line and below some other scripts, such as jquery.min.js, site.js, etc.

Also check that the "_ValidationScriptsPartial.cshtml" file has lines like this:

<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>

CodePudding user response:

place this under your view @Html.ValidationSummary(false)

 <input type="text" asp-for="Naam" />

also add required for the validate item

 <input type="text" asp-for="Naam" required/>
  • Related