开发者

StringLength attribute, client side validation and a membership provider

开发者 https://www.devze.com 2023-03-01 22:20 出处:网络
How do I pass a value from Membership Provider (taken from web.config开发者_如何学Go) to Validation Attributes in AccountModels in default MVC 3 project?

How do I pass a value from Membership Provider (taken from web.config开发者_如何学Go) 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号