Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
Dear All,

I want to add attributes to model class properties based on some conditions

example:

Suppose the following EmployeeModel Class:

C#
public class EmployeeModel
    {
        public int EmployeeId { get; set; }

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


I want to add the Required attribute on EmployeeName Based on Some Condition.

How can i implement that?
Posted

1 solution

Here is the updated code


Class file
C#
public class ConditionalRequired : ValidationAttribute, IClientValidatable
    {
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var mcvrTwo = new ModelClientValidationRule();
            mcvrTwo.ValidationType = "contactnovalid";
            mcvrTwo.ErrorMessage = "Contact No is not valid.";
            mcvrTwo.ValidationParameters.Add
            ("contactnoregex", @"\b\d{10}\b");
            return new List<ModelClientValidationRule> { mcvrTwo };
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var obj = validationContext.ObjectInstance as Customer;
            if (obj.CustomerID == 1)
            {
                return ValidationResult.Success;
            }
            return new ValidationResult("Contact No is not valid");
        }
    }



CSHTML file
JavaScript
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/MicrosoftAjax.js"></script>

<script type="text/javascript">
    $.validator.addMethod("contactnovalid", function (value, element, contactnoregex) {
        var patt = new RegExp(contactnoregex);
        if (patt.test(value))
            return true;
        return false;
    });
    $.validator.unobtrusive.adapters.add("contactnovalid", ["contactnoregex"], function (options) {
        options.rules["contactnovalid"] = options.params.contactnoregex;
        options.messages["contactnovalid"] = options.message;
    });
</script>
 
Share this answer
 
v3
Comments
_ProgProg_ 13-Dec-15 4:16am    
Can you give me more details of how to use this?
Rajdeep Debnath 13-Dec-15 4:34am    
Yes, can you let me know the condition also? Will it check other model property?

the steps are
1. Create a new class and derive the class from ValidationAttribute class (or add the above code). This will create custom attribute.
2. The IsValid method will return true or false based on EmployeeName value entered by the user/system, but here logic can vary based on your condition
3. Apply the attribute on your model property
_ProgProg_ 13-Dec-15 4:56am    
Actually it did the purpose but the code is implemented after post action and i want that code run on rendering view.
Rajdeep Debnath 13-Dec-15 5:06am    
Can you provide me bit more detail....about rendering view part
_ProgProg_ 13-Dec-15 5:20am    
It's a simple Create view with property EmployeeName.
For testing now i am using ConditionalRequired with always return false;
Here is My Code:
if (ModelState.IsValid)
{
//Some Code For Insert
//Some Code For Redirect
}
else
return View();

As You Can See, Now i added Else Statement to return to the same view and view the message that employee name is not valid.
So this is not occured until i press the Create button.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900