I have an ASP.NET Core (7.0) web app and I'm unable to get client side validation to work in VS2022 (17.6.2 - 64 bit, Win 10). I'm expecting to see a validation message on screen as I type or if I cause the input box to loose focus but I see no validation text. I type in a number outside the range or an invalid format email address. There are no errors in the browser console window.
What am I doing wrong?
I created a new ASP.NET Core project, added some properties to the model on the template Privacy page and then added the elements to the page and included _ValidationScriptsPartial. The 3 jQuery .js files are included from the Layout or _ValidationScriptsPartial. I expect to see a validation message but I don't.
Model:
public class PrivacyModel : PageModel
{
private readonly ILogger<PrivacyModel> _logger;
[BindProperty]
[Required]
[Range(0, 50, ErrorMessage = "Number is invalid")]
public int TestNumber { get; set; }
[BindProperty]
[Required]
[EmailAddress(ErrorMessage = "Email address is invalid")]
public string TestString { get; set; }
public PrivacyModel(ILogger<PrivacyModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
}
}
Page:
@page
@model PrivacyModel
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>
<p>Use this page to detail your site's privacy policy.</p>
<label asp-for="TestNumber" >Enter number</label>
<input id="idtn" name="testn" type="text" asp-for="TestNumber" />
<span asp-validation-for="TestNumber"/>
<label asp-for="TestString" >Enter string</label>
<input id="idts" name="tests" type="text" asp-for="TestString" />
<span asp-validation-for="TestString" />
@section Scripts{
<partial name="_ValidationScriptsPartial" />
}
From the given code, it looks like the issue is within the name
property of the input
tag. asp-validation-for
will try to find the input
tag with the name TestNumber
but the name is testn
.
Try the below code, it should work:
<input id="idtn" name="TestNumber" type="text" asp-for="TestNumber" />
<span asp-validation-for="TestNumber"/>
You can remove the name
property; asp-for
will do that for you.