简体   繁体   中英

Validating password using javascript and razor

I'm trying to make a simple login form with password encrypting and validating in asp-mvc.

I have the following login form (partial code only):

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "loginForm" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>

        //some fields
        ... 

        // password
        <div class="editor-label">
            @Html.LabelFor(model => model.Password)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)
        </div>

        //some fields
        ... 
}

In addition, I have the following javascript code (I know that the encryption is not the safest that way but that's more than enough for me)

$("#loginForm").submit(function (e) {
    var pass = $("#Password").val();
    var passMD5 = CryptoJS.MD5(pass);
    $("#Password").val(passMD5);
});

And a C# ViewModel which have the following attribute

[Required(ErrorMessage = "Can't leave password field empty")]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }

When someone enters a password I encrypt the password and then send it to the server but then the validation is calculated for the encrypted password.

How can I perform some validations on the password field and have the errors be displayed in the the Html.ValidationMessageFor spot?

If you want validation to happen on client side itself means try calling these two js along with the latest jquery library..If any of the field doesnt satisfy the condition means it will show the error message on the client side itself and it will not hit the server side coding..

http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.js

http://ajax.aspnetcdn.com/ajax/mvc/5.1/jquery.validate.unobtrusive.min.js

You can validate the form before you change the password by doing the following:

$("#loginForm").submit(function (e) {
    if (!$("#loginForm").valid()) {
        return false;
    }
    var pass = $("#Password").val();
    var passMD5 = CryptoJS.MD5(pass);
    $("#Password").val(passMD5);

 });

If validation fails you will see the client side message, and if it succeeds an encrypted password will be passed to the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM