I am trying to add some form validation to a few of my fields. I have a dropdown and an input box. Both of the inputs need validation. My goal is to display an error message to the user if either one are not valid. The form allows the user to create a copy of an existing book, with a new author. The dropdown has a list of books from the database, and the user types in the name of the new Author in the text box. The submit button creates a copy of the existing book with a new author.
Using jQuery, jquery.validate.js, and jquery.validate.unobtrusive.js I was able to accomplish displaying the error message to the user, but the check happens as soon as the page loads, so the error messages appear as soon as the page loads. (Maybe I'll need a hidden field, or I will have to modify my HttpGet handler).
Right now if the user tries to submit the form without selecting a book and/or typing in the author's name, the route remains the same, but the form goes away and there is a json object that displays on the screen with a 400 status and it says "The bookName field is required" and "The author field is required". I just want red text next to the input fields that says they cannot be left empty, how can I accomplish this? Thanks!
My Model:
public int ID { get; set; }
[Required]
public string bookName { get; set; }
[Required]
public string Author { get; set; }
My cshtml:
<form method="post" asp-controller="Index" asp-action="Index" role="post">
<div class="form-group">
<label asp-for="bookName"></label>
<select name="bookName" asp-items="@(new SelectList(ViewBag.message, "ID", "bookName"))">
</select>
<span asp-validation-for="bookName">Please select a book.</span>
</div>
<div class="form-group">
<label asp-for="Author"></label>
<input asp-for="Author" class="form-control" />
<span asp-validation-for="Author">Please type in the author's name.</span>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</form>
My Controller:
[HttpGet("[action]")]
[Route("/Index")]
[Produces("application/json")]
public IActionResult Index()
{
return View();
}
[HttpPost("[action]")]
[Route("/Index")]
[Produces("application/json")]
public async Task<IActionResult> Index([FromForm] bookModel model)
{
if(ModelState.IsValid)
{
//do stuff
return View(model)
}
else
{
//display an error message & remain on same page
}
}
