Search code examples
c#jqueryasp.netasp.net-coreunobtrusive-validation

ASP.NET Core Unobtrusive Client Side Validation Form onsubmit fires even on validation failure


Note: This is related to .NET Core v2.0. You may find related posts but they don't address the issue I'm facing.

I'm applying Unobtrusive Client side validation with code as below:

<form asp-route-returnurl="@ViewData["ReturnUrl"]" method="post" onsubmit="showPleaseWait()" >
    <div asp-validation-summary="All" class="text-danger"></div>
    <div class="form-group">
        <label asp-for="Username" class="control-label"></label>
        <input asp-for="Username" class="form-control" placeholder="Username"  />
        <span asp-validation-for="Username" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Password" class="control-label"></label>
        <input asp-for="Password" value="" class="form-control" placeholder="Password" />
        <span asp-validation-for="Password" class="text-danger"></span>
    </div>
    <div class="form-group">
        <button type="submit"  class="btn btn-success btn-lg" style="margin:auto;display:block">Log in</button>
    </div>
</form>

Good thing is it's performing validation on client side.

However, form.onsubmit event is fired even when the validation fails. As a result my showPleaseWait method is called. I believe it shouldn't be called since the form is not submitted yet due to validation failure.

Below is the model:

public class LoginViewModel
{
    [Required]        
    public string Username { get; set; }

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }
}

Any solution or workaround would be highly appreciated.


Solution

  • The jQuery Unobtrusive Validation and higher-level jQuery Validation plugins do not block the submit event from being raised, which, as you've noted, means your showPleaseWait() function will be called whenever the user attempts to submit the form.

    One option for making this work is to query the status of validation from within your showPleaseWait function, before attempting to run your own code. Here's an example:

    function showPleaseWait() {
        if ($("form").valid()) {
            // Your code here.
        }
    }
    

    This implementation takes advantage of jQuery Validation's valid function, which:

    Checks whether the selected form is valid or whether all selected elements are valid.

    I've just used a simple $("form") selector above, but this may need to be more specific if you have multiple forms on a single page, etc.