MVC3 Validation based on Users Role
We are using MVC3 with unobstructuve validation, all is fine; we got our custom validations working on the server as well as on the client.
We are also using the build-in asp.net Role provider. We have particular Views that we use for different Roles. Some of the fields (properties of the ViewModel) are Required based on the Role of the logged-in user.
My question is: How do we make a ValidationAttribute based on a Role? We want to make a property Required when the user is Normal User; but we don't want to make that field required when the user is an Administrator. But we do want to use the same view.
I know we can create a custom ValidationAttribute (creating a class that derives from ValidationAttribute) I suppose that will work fine for Server-Side validation. But we really want to validate this Client-Side.
I reckon we implement the IClientValid开发者_运维技巧atable in our above ValidationAttribute and write some jQuery to make an Ajax call back to the server to check the current logged in user and its roles. But this will make us do an Ajax call every time the specific property changes, and the logged-in user will not change.
What is the right way to do this? Or should we create different ViewModels for different logged in user?
Please let me know when my above explanation doesn't make sense, I can add some example code when needed.
Any help is appreciated.
Thanks,
Pim
I think you can indeed implement a custom ValidationAttribute that also implements the IClientValidatable. But then you could just "reuse" the unobtrusive required validation for the client side:
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
if ( <your condition, e.g. if user has a certain role> )
yield return new ModelClientValidationRequiredRule(<error message>);
}
This should generate the same unobtrusive required attributes on the input as the RequiredAttribute, but only if your condition is met.
精彩评论