0

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.

Liam
  • 27,717
  • 28
  • 128
  • 190
Roberto Correia
  • 1,696
  • 5
  • 20
  • 36
  • Possible duplicate of [How to fire jQuery function only if form is valid](http://stackoverflow.com/questions/5052315/how-to-fire-jquery-function-only-if-form-is-valid) – Liam Sep 27 '16 at 14:04

2 Answers2

0

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!

Karel Tamayo
  • 3,690
  • 2
  • 24
  • 30
  • Just use `@Html.ValidationMessageFor(v => v.property)`. That's it. Writing all this just re-invents the wheel when it's all done for you out of the box. – Liam Sep 27 '16 at 14:10
0

Not the best option, but I solved with the following changes:

on a css, put the following content (to hide the list):

.validation-summary-erros {
  display: none;
}

on Login.cshtml (call a toastr for every error):

<script type="text/javascript">
  $(".validation-summary-erros ul li")
    .each(function() {
      toastr.error($(this).text());
    });
</script>

I have other options, like:

  • create a custom TagHelper: too much work for this.
  • on the controller, pass a variable with the error to view: works, but I prefer a AddModelError option, because this is a error (validation error)!

I'm still looking for a better aproach!

Roberto Correia
  • 1,696
  • 5
  • 20
  • 36
  • You don't need to add the error messages yourself. Just use the Razor helper methods `@Html.ValidationMethodFor(v => v.property)`. The built in libraries do the rest for you – Liam Sep 27 '16 at 14:07
  • I think this is actually a pretty good solution. I've updated my answer though in case you want to see how can be done with the approach we saw first. – Karel Tamayo Sep 27 '16 at 14:07
  • @Liam, `@Html.ValidationMethodFor` return a error `'IHtmlHelper' does not contain a definition for 'ValidationMethodFor'.` – Roberto Correia Sep 27 '16 at 16:16
  • Typo that should be `ValidationMessageFor`. Your intellisense should auto complete this. I'd really spend some time learning how [MVC validation works](http://www.asp.net/mvc/overview/getting-started/introduction/adding-validation). You really are making this all very hard for yourself here – Liam Sep 28 '16 at 08:21
  • @Liam I don't get. I know how to use `ValidationMessageFor` for a model field. This works good. But, when the user put a invalid username and invalid password, it's not a invalid field on model. It's a "general" error. If in my controller, I place `ModelState.AddModelError(string.Empty, "Custom Error Message");` the `ValidationMessageFor` don't works for this (at least I don't know how). – Roberto Correia Sep 28 '16 at 13:30