0

Why does the console display validation errors but ValidationSummary does not display them? How to make ValidationSummary display User Validation failed?

photo of the console

RegisterView Code

@Html.ValidationSummary()

<h4>Name</h4>
@Html.TextBoxFor(model => model.Name)

<h4>Email</h4>
@Html.TextBoxFor(model => model.Email)

<h4>Pasword</h4>
@Html.TextBoxFor(model => model.Pasword)

<h4>ConfirmPasword</h4>
@Html.TextBoxFor(model => model.ConfirmPasword)

<h4>RememberMe</h4>
@Html.CheckBoxFor(model => model.RememberMe)

<button type="submit">Register</button>
photo of the Controller

Controller code

[HttpPost("Register")]
        public async Task<ActionResult> Register(RegisterViewModle modle)
        { 
            if (!ModelState.IsValid) { return View(modle); }
            var user = new ApplicationUser { Email = modle.Email, UserName = modle.Name };
            var result = await _UserManeger.CreateAsync(user, modle.Pasword);
            var roleResult = await _UserManeger.AddClaimAsync(user, new Claim(ClaimTypes.Role, "User"));
            if (result.Succeeded & roleResult.Succeeded)
            {
                await _SignInManager.SignInAsync(user, isPersistent:false);
                return Redirect("https://localhost:7195/user");
            }
           
            return View(modle);
        }
Vladlen
  • 37
  • 7
  • On finding that the user name or email already exists in your db table, you need to add model Error before returning the View to the UI. See the usage of `AddModelError` in this [article](https://www.tutorialsteacher.com/mvc/htmlhelper-validationsummary) – Anand Sowmithiran Jun 07 '22 at 05:01
  • Refer to this very nicely written SO answer on error handling including about `AddModelError`, https://stackoverflow.com/a/41689408/14973743 – Anand Sowmithiran Jun 07 '22 at 05:04

2 Answers2

1

For your customs error messages you need to add ModelState.AddModelError method.

 if(emailAlreadyExists)
            {
                //adding error message to ModelState
 ModelState.AddModelError("email", "Email Already Exists.");
    
              
            }

ModelState treats your errors exactly the way it treats errors generated by model binding. When you add an error using AddModelError, the ModelState’s IsValid property is automatically set to false.

Also The ValidationSummary() method will automatically display all the error messages added into the ModelState.

The Basis of Validation

How Model State works

Amit Kotha
  • 1,641
  • 1
  • 11
  • 16
0

If you cannot see the error when debugging, maybe try the code in your UserValidator as below:

            List<IdentityError> errors = new List<IdentityError>();
            if (userManager.FindByEmailAsync(user.Email) != null)
            {
                errors.Add(new IdentityError { Code = "EmailFilad", Description = "Эта почта уже используется" });
            }
            if (errors.Count == 0)
            { return IdentityResult.Success; }


            else return IdentityResult.Failed(errors.ToArray());

enter image description here

If you want to see the error in the view, you can add below code in your Register action .

    [HttpPost]
    public async Task<ActionResult> Register(RegisterViewModle modle)
    { 
        if (!ModelState.IsValid) { return View(modle); }
        var user = new ApplicationUser { Email = modle.Email, UserName = modle.Name };
        var result = await _UserManeger.CreateAsync(user, modle.Pasword);
        var roleResult = await _UserManeger.AddClaimAsync(user, new Claim(ClaimTypes.Role, "User"));
        if (result.Succeeded & roleResult.Succeeded)
        {
            await _SignInManager.SignInAsync(user, isPersistent:false);
            return Redirect("https://localhost:7195/user");
        }
       foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
        return View(modle);
    }

Result:

enter image description here

Qing Guo
  • 6,041
  • 1
  • 2
  • 10