简体   繁体   English

ASP.NET MVC中更改密码的可选验证

[英]Optional Validation for Change Password in ASP.NET MVC

I have the following model 我有以下型号

public AccountInfo {

    // loads of other property here as well.

    public string Password { get; set; }

    public string NewPassword { get; set; }

    [Compare("NewPassword", ErrorMessage = "New Passwords dont match.")]
    public string ConfirmNewPassword { get; set; }

}

I am using data annotations to display client side validation message. 我正在使用数据注释来显示客户端验证消息。

Now I am working on the change user profile details page. 现在,我正在“更改用户个人资料详细信息”页面上。

What I am required to do is, Along with the other details such as email, full name, address etc, I have to show 3 fields namely 我需要做的是,连同其他详细信息,例如电子邮件,全名,地址等,我必须显示3个字段,即

  • Current password 当前密码
  • New password 新密码
  • Confirm New password 确认新密码

Now the scene is that these are optional fields and user may not fill it. 现在的场景是这些是可选字段,用户可能无法填写。 But when he does, I want to make sure all the 3 fields are filled. 但是,当他这样做时, 我要确保所有3个字段都已填写。 , if not I want to show some validation error using data annotation. ,如果不是,我想使用数据注释显示一些验证错误。

Any Thoughts ? 有什么想法吗 ?

There isn't any built in data annotation for this. 对此没有任何内置数据注释。 You could create your custom attribute to do the validation, but it's not easy. 您可以创建自定义属性来进行验证,但这并不容易。 As such, I would suggest you to use Jquery Validation / Javascript to handle this. 因此,我建议您使用Jquery Validation / Javascript处理此问题。

Basically you would want to override the submit event and do your own validation logic in there. 基本上,您将要覆盖Submit事件并在其中执行自己的验证逻辑。 You code will be similar to this: 您的代码将与此类似:

function SubmitToServer() { 
    if ($('#Password').length == 0 || ($('#Password').length > 0 && $('#NewPassword ').length > 1 && $(formId).valid()) {
        $(formId).submit();
    }
}

You can use [Required] to tell the RAZOR that these are must or mandatory like that.. 您可以使用[Required]告诉RAZOR,这些是必须的或强制性的。

[Required]
public string Password { get; set; }

 [Required]
 public string NewPassword { get; set; }

 [Required]
 [Compare("NewPassword", ErrorMessage = "New Passwords dont match.")]
 public string ConfirmNewPassword { get; set; }

If you want to Provide range of value means use this one - [Range(1, 100)] 如果要提供值的范围,则表示使用此值- [Range(1, 100)]

If you want to use password lenght means use this one - [StringLength(5)] 如果要使用密码长度,请使用此密码- [StringLength(5)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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