Search code examples
javascriptc#jqueryasp.net-mvcunobtrusive-validation

Call a javascript function when form is not valid


I have experience with web frameworks for PHP (Laravel) and Python (Django). But I'm lost with C# and ASP.NET!

I'm trying to make a login page with ASP.NET core and C#. Using an example, I have a login form, with username and password input fields:

<div asp-validation-summary="None" class="text-danger"></div>
<label asp-for="Username"></label>
<input asp-for="Username" class="form-control" />
<span asp-validation-for="Username" class="text-danger"></span>

<label asp-for="Password"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>

and in my view-model:

[Required(ErrorMessage = "** Localized error message **")]
[Display(Name = "Username:", Prompt = "Username")]
public string Username { get; set; }

[Required(ErrorMessage = "** Another localized error message **")]
[DataType(DataType.Password)]
[Display(Name = "Password:", Prompt = "Password")]
public string Password { get; set; }

Everything works ok! If I don't put a username and/or password on form, the localized error message appears correctly. But if I provide an invalid username/password, a generic error (with ul, li) appears at top of the form. It's ok, but I like to display a toastr in place, like:

toastr.error(errorMessageOfInvalidLogin);

How I can check if a form is valid in client-side? I already included the toastr, and I can call 'manually'. But I don't have any ideia how to call this javascript only when form is invalid, and how recover the error message.


Solution

  • In case you need to get the value in razor:

    You can remove the validation summary tag:

    @*<div asp-validation-summary="All" class="text-danger"></div>*@
    

    Render this inside the form:

    @if (ViewData.ModelState.Any(x => x.Key == string.Empty))
                    {
                        var errors = ViewData.ModelState[string.Empty].Errors.Select(e => e.ErrorMessage).Aggregate("", (current, error) => current + error);
                        <input type="hidden" id="error" value="@errors" />
                    }
    

    In the scripts section:

    <script>
    
    $(function() {
                var error = $("#error").val();
                if (error != undefined) {
                    $.toaster({ message: error, title: 'Error', priority: 'danger' });
                }
            })
    
    </script>
    

    Wanna take a look? Click here!