ModelState IsValid returns False Using ASP.NET Core 5 MVC Identity with UserName

user3596617

I'm trying to accomplish login functionality using UserName instead of Email to Login.

I'm using Bootstrap Modal dialog for loging in users with jquery and ajax for error handling.

The UserName is not an email address so ModelState IsValid always returns false. If I hard code an email address in the javascrip file then all works.

Is there anyway around this issue. Any help would be much appreciated.

    <div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
  <div class="modal-header">
    <h5 class="modal-title" id="exampleModalLabel">Login</h5>
    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
  </div>
  <div class="modal-body">
    <form id="UserLoginForm" asp-controller="UserAuth" asp-action="login">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <input type="hidden" asp-for="LoginInValid" />
        <div class="form-group row mb-3">
            <label asp-for="UserName" class="col-md-4 col-form-label"></label>
            <div class="col-md-8">
                <input asp-for="UserName" placeholder="User Name" class="form-control" />
                <span asp-validation-for="UserName" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group row mb-3">
            <label asp-for="Password" class="col-md-4 col-form-label"></label>
            <div class="col-md-8">
                <input asp-for="Password" placeholder="Password" class="form-control" />
                <span asp-validation-for="Password" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group-row">
            <div class="col-md-8 offset-md-4">
                <div class="form-check">
                    <input asp-for="RememberMe" class="form-check-input" />
                    <label asp-for="RememberMe" class="col-md-4" col-form-label"></label>
                </div>
            </div>
        </div>
    </form>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
    <button type="button" id="login" name="login" class="btn btn-primary">Login</button>
  </div>
</div>
 [AllowAnonymous]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginModel loginModel)
    {
        loginModel.LoginInValid = "true";

        if (ModelState.IsValid)
        {
            var result = await _signInManager.PasswordSignInAsync(loginModel.UserName, loginModel.Password, loginModel.RememberMe, lockoutOnFailure: false);

            if (result.Succeeded)
            {
                loginModel.LoginInValid = "";
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Invalid login attempt");
            }
        }
        return PartialView("_UserLoginPartial", loginModel);
    }

Error handling is not displayed

(function () {
    var userloginButton = $("#UserLoginModal button[name='login']").click(onUserLoginClick);

    function onUserLoginClick() {

        var url = "UserAuth/Login";

        var antiForgeryToken = $("#UserLoginModal input[name='__RequestVerificationToken']").val();

        var username = $("#UserLoginModal input[name = 'UserName']").val();
        var email = "mydomain.com"
        /*var email = $("#UserLoginModal input[name = 'Email']").val();*/
        var password = $("#UserLoginModal input[name = 'Password']").val();
        var rememberMe = $("#UserLoginModal input[name = 'RememberMe']").prop('checked');

        var userInput = {
            __RequestVerificationToken: antiForgeryToken,
            UserName: username,
            Email: email,
            Password: password,
            RememeberMe: rememberMe
        };
    }
});    

LoginModel

public class LoginModel
{
    [Required]
    [Display(Name = "User Name")]
    [StringLength(25, MinimumLength = 2)]
    public string UserName { get; set; }

    [Required]
    [StringLength(100, MinimumLength = 2)]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [StringLength (100, MinimumLength = 2)]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    public bool RememberMe { get; set; }

    public string LoginInValid { get; set; }
}
sstr27

LoginModel has UserName, Email, and Password all marked as "Required", so ModelState will not be valid unless all are provided.

You'll need to either provide values for each of these (I don't see any Email input in your HTML markup) or remove the [Required] annotation from the LoginModel properties you don't want to provide.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

ModelState.IsValid always returns false in ASP.NET Core 6.0 MVC

ASP.NET MVC 5 ModelState.IsValid is always returning false in MVC

ASP.NET 5, MVC6, WebAPI -> ModelState.IsValid always returns true

asp.net mvc2 save selected fileupload (when ModelState.IsValid = false)

ModelState.IsValid keeps being false because of SelectList in ASP.NET Core

ASP.NET and EF Core - ModelState.IsValid always returns true for models generated by Scaffold-DbContext

ASP.NET MVC Core 3.0 - Why API Request from body keeps returning !ModelState.IsValid?

ASP.NET MVC 5 Identity 2 PasswordSignInAsync method always returns false

What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

Identity in ASP.NET MVC Framework using Identity Core

ASP.NET Core returns InternalServerError while using Identity server

Pass username into headers using httpContext asp.net core mvc

ModelState.IsValid is false

ModelState.isValid - false

ModelState.IsValid returns False even if the required property is valid

Use Username instead of Email for identity in Asp.net mvc5

ModelState.IsValid = false MVC 4 Entity Framework

ASP.NET Core 2.0 Identity: SignInManager.IsSignedIn(User) returns false after signing in

ASP.NET Core Identity 2: User.IsInRole always returns false

How to display specific ModelState errors in ASP.NET Core MVC?

Globally ModelState Validation In Asp.Net Core Mvc

ASP.NET MVC 5 "When ModelState is Invalid"

ASP.NET Core MVC MySQL Identity

Using ASP.NET Identity in an ASP.NET Core MVC application without Entity Framework and Migrations

User.Identity.Name returns null in ASP.NET Core MVC application

Asp.net core identity change username/email

ModelState.isvalid returning false?

VB.NET - MVC ModelState.IsValid is always true

In .Net Core API, ModelState.IsValid is not catching Required parameters