Search code examples
c#asp.net-corevalidationrazor-pagesasp.net-core-3.1

ASP.NET Core Razor page Client Side Validation not displaying error message


I am not able to get the client side validation to display the error message for WebForm.FullName, when that field is submitted with an empty string. It does prevent the webpage from posting to the server on submit, when this field is empty, so I know the validation is somewhat working. Just Can't figure out what I'm doing wrong in regards to the error message not displaying.

So far I've tried with no success:

  1. Putting the jQuery validator references in the WebForm.cshtml page.
  2. Adding the fields with ? marks, making them nullable in WebForm.cs.
  3. last attempt was to add a z-index.

enter image description here

WebForm.cshtml

    <div>
    <form method="post">
        <div class="w-75" style="margin:0 auto; border: 1px solid lightgrey; padding:20px;">
            <div class="row justify-content-center">
                <div class="form-group col-md-4" style="padding:5px;">
                    <label for="WebForm.FullName">Name:</label>
                    <input asp-for="WebForm.FullName" name="FullName" size="25" style="text-align:center;">
                    <span asp-validation-for="WebForm.FullName" class="text-danger" style="z-index:999;"></span>
                </div>
            </div>
            <div class="row justify-content-end">
                <div class="form-group" style="padding:5px;">
                    <button type="submit" class="btn btn-primary">Submit</button>
                </div>
            </div>
        </div>
    </form>
    </div>

WebForm.cshtml.cs

    public class WebFormModel : PageModel
{
    //This is the Data Binding model class. 
    [BindProperty]
    public WebForm WebForm { get; set; }

    public void OnGet()
    {
        
    }

    //Handle form post here. 
    public void OnPost(WebForm WebForm)
    { 
    
    }
}

WebForm.cs

    public class WebForm
{
    [Required(ErrorMessage="Full name is required.")]
    public string FullName { get; set; }
}

Solution

  • My Colleague helped me figure out the issue: This line of html in the WebForm.cshtml file

        <input asp-for="WebForm.FullName" name="FullName" size="25" style="text-align:center;">
    

    should be:

        <input asp-for="WebForm.FullName" name="WebForm.FullName" size="25" style="text-align:center;">