ha169169
ha169169

Reputation: 3

Validation model of Password (Razor Page)

In my pageMode Code

l` public class LoginViewModel
    {
        [Required]
        public string LoginId { get; set; } = null!;

        [Required]
        public string  Password { get; set; } = null!;
    }

    [BindProperty]
    public LoginViewModel Input { get; set; } = null!;`

And in view

<div asp-validation-summary="ModelOnly" class="text-danger"></div>
                <div class="form-group-with-label mb-4">
                    <label>UserId</label>
                    <input asp-for="Input.LoginId" class="form-control-input" autocomplete="off" />
                    <span asp-validation-for="Input.LoginId" class="text-danger"></span>
                </div>

                <div class="form-group-with-label login-input-password mb-2">
                    <label>Password</label>
                    <input class="form-control-input" type="password" asp-for="Input.Password" autocomplete="off" />
                    <span class="fa fa-eye" id="togglePassword"></span>
                    <span asp-validation-for="Input.Password" class="text-danger"></span>
                </div>

When I submit Login button -> all case ModalState Valid or Invalid when return Page() input type Password always clear value and when I change type of Password from password to text, every thing will OK.

Please help to keep my input password all cases(After post value)

Upvotes: 0

Views: 304

Answers (1)

Xinran Shen
Xinran Shen

Reputation: 9993

One method is set the type to text in password input then change it in JavaScript, the code like

<form method="post">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <div class="form-group-with-label mb-4">
        <label>UserId</label>
        <input asp-for="Input.LoginId" class="form-control-input" autocomplete="off" />
        <span asp-validation-for="Input.LoginId" class="text-danger"></span>
    </div>

    <div class="form-group-with-label login-input-password mb-2">
        <label>Password</label>
        <input id="passwordInput" class="form-control-input" type="text" asp-for="Input.Password" autocomplete="off" />
        <span class="fa fa-eye" id="togglePassword"></span>
        <span asp-validation-for="Input.Password" class="text-danger"></span>
    </div>
    <button>Submit</button>
</form>



@section Scripts{
    <script type="text/javascript">

        $(document).ready(function () {
            var passElem = $("#passwordInput");
            passElem.prop("type", "password");
        });
    </script>
}

But I don't recommend this method. In my opinion, You should let the user decide whether to allow the browser to remember their username and password, Just like this:

enter image description here

===============update================

@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
}

Upvotes: 0

Related Questions