2

Is it possible to make required for only specified roles to model field on data anotation?

For Example:

[Display(Name = "Kurum")]
[Required(ErrorMessage = "Kurum Alanı Girişi Zorunludur.",Roles="user")]
public decimal? KurumKodu { get; set; }

I know there isnt parameter like Required(Roles="xxxx") , but I wonder is there any other solution about this?

Thanks.

tcetin
  • 979
  • 1
  • 21
  • 48
  • 1
    You would have to create your own validation attribute (and implement `IClientValidatable` for client side validation) –  Oct 13 '16 at 07:47
  • Have you got any code samples? – tcetin Oct 13 '16 at 07:48
  • @kodcu Please check http://stackoverflow.com/questions/7390902/requiredif-conditional-validation-attribute – kamil-mrzyglod Oct 13 '16 at 07:49
  • 1
    Refer [The Complete Guide To Validation In ASP.NET MVC 3 - Part 2](http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2) for a good guide to creating your own validation attributes –  Oct 13 '16 at 07:49
  • @kodcu Please check [Role based Authorization](https://docs.asp.net/en/latest/security/authorization/roles.html) – huse.ckr Oct 13 '16 at 07:50
  • @StephenMuecke Yes we do by custom validation. – Power Star Oct 13 '16 at 09:57
  • @user3060520 Did you understand OP question? – Power Star Oct 13 '16 at 09:58

3 Answers3

2

You have to create custom validation attribute for this. Below code may help you to do this.

      public class RequiredIfAttribute : RequiredAttribute
        {
            private string PropertyName { get; set; }
            private object DesiredValue { get; set; }

            public RequiredIfAttribute(string propertyName, object desiredvalue)
            {
                PropertyName = propertyName;
                DesiredValue = desiredvalue;
            }

            protected override ValidationResult IsValid(object value, ValidationContext context)
            {
                object instance = context.ObjectInstance;
                Type type = instance.GetType();
                Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
                if (proprtyvalue.ToString() == DesiredValue.ToString())
                {
                    ValidationResult result = base.IsValid(value, context);
                    return result;
                }
                return ValidationResult.Success;
            }
        }

Then you have to decorate your property with this attribute (read the comments in code for understanding)

        public class User
        {
            /// <summary>
            /// Gets or Sets Usertype.
            /// </summary>
            public string UserType { get; set; }

            /// <summary>
            /// Gets or Sets KurumKodu.
            /// Here "Usertype" is property. In that you have to assign current user's role.
            /// "user" is constant role. If  "UserType" has value as "user" then this will be required.
            /// </summary>
            [RequiredIf("UserType", "user", ErrorMessage = "It is required")]
            public decimal KurumKodu { get; set; }
        }

If you want to add Client Side validation(unobtrusive) then, please see below link.

RequiredIf Conditional Validation Attribute

Community
  • 1
  • 1
Power Star
  • 1,724
  • 2
  • 13
  • 25
0

You can use

HttpContext.Current.User.IsInRole("USER_ROLE")

in your custom validation attribute class

Vincent Nabet
  • 128
  • 1
  • 6
-2

I tried different approaches but I came to this point that the best place to do that is on view. Something like:

 @if (User.IsInRole("SystemAdministrator"))
    {
     <td>@Html.DisplayFor(model => model.KurumKodu)</td>
    }
Hadee
  • 1,392
  • 1
  • 14
  • 25
  • OP is wanting conditional validation and this has nothing to do with it (its not even generating a form control) –  Oct 13 '16 at 21:44
  • conditional validation is for showing the property and this piece of code does exactly the same.not even generating a form control? What exactly you mean? – Hadee Oct 13 '16 at 21:50
  • Read the question. OP whats to make a property Required (i.e it must have a value when edited in a form) based on the role of the user (and validation has nothing to do with _showing the property_ - its for validating the the value of a property meets a condition) –  Oct 13 '16 at 21:52
  • The question doesn't imply if it is not required for other than specific role. If the property isn't required at all for other roles, my answer works. – Hadee Oct 13 '16 at 21:58
  • You clearly do not understand the question.OP is applying a **validation** attribute to the property. The purpose of a validation attribute is to perform validation when editing the property in a view to ensure that it meets a condition - in this case that the value entered in the text box is **required** (cannot be `null`) if the user has a certain role (and if the user does not have that role, then it is allowed to be `null`) –  Oct 13 '16 at 22:01
  • And you clearly don't understand my last comment above. – Hadee Oct 13 '16 at 22:07
  • I give up. (your answer has nothing at all to do with the question) –  Oct 13 '16 at 22:09