StringLength attribute, client side validation and a membership provider

血红的双手。 提交于 2019-12-08 11:19:32

问题


How do I pass a value from Membership Provider (taken from web.config) to Validation Attributes in AccountModels in default MVC 3 project?

Membership.MinRequiredPasswordLength

returns value obtained from web.config and Register.cshtml view uses it:

<p>
Passwords are required to be a minimum of @Membership.MinRequiredPasswordLength
characters in length.
</p>

But it seems that ViewModel in AccountModels file have the values hard-coded in:

[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }

So how do I pass the value from web.config to MinimumLength parameter?


回答1:


You won't be able to specify an attribute property dynamically like you would like. That is why the templates have it hard-coded. The workaround to still use data annotations would be to have your view model implement IValidatableObject and have it check the password against Membership.MinRequiredPasswordLength. Another option would be to create an attribute that inherits from ValidationAttribute and checks against Membership.MinRequiredPasswordLength.

David Hayden has a post covering both of these options.

For the client side, you would need to implement IClientValidatable on the model or the custom attribute. Here is another answer that shows an example. You would also need to add the client side validation function, and you could use @Membership.MinRequiredPasswordLength inside your Razor view to pull in the value.



来源:https://stackoverflow.com/questions/5859880/stringlength-attribute-client-side-validation-and-a-membership-provider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!