Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How to put conditional data annotations? How to prepare data annotations validation when property value required depends on other property value?

I have coded as below:

[RequiredIf("property_name=="property_Value"", ErrorMessageResourceType = typeof(Resources.resfilename), ErrorMessageResourceName = "ErrMessage")]
        public int? propertyname { get; set; }

How to generate required-if class?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
724 views
Welcome To Ask or Share your Answers For Others

1 Answer

Create a class as below:

using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace BusinessModels
{
    public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
    {
        private readonly string _condition;

        public RequiredIfAttribute(string condition)
        {
            _condition = condition;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            Delegate conditionFunction = CreateExpressionDelegate(validationContext.ObjectType, _condition);

            bool conditionMet = (bool) conditionFunction.DynamicInvoke(validationContext.ObjectInstance);

            if (conditionMet)
            {
                if (value == null)
                {
                    return new ValidationResult(FormatErrorMessage(null));
                }
            }
            return null;
        }

        private Delegate CreateExpressionDelegate(Type objectType, string expression)
        {
            // TODO - add caching
            var lambdaExpression = CreateExpression(objectType, expression);
            Delegate func = lambdaExpression.Compile();
            return func;
        }

        private LambdaExpression CreateExpression(Type objectType, string expression)
        {
            // TODO - add caching
            LambdaExpression lambdaExpression =
                System.Linq.Dynamic.DynamicExpression.ParseLambda(
                    objectType, typeof(bool), expression);
            return lambdaExpression;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            string errorMessage = FormatErrorMessage(metadata.GetDisplayName());

            Expression expression = CreateExpression(metadata.ContainerType, _condition);
            var visitor = new JavascriptExpressionVisitor();
            string javascriptExpression = visitor.Translate(expression);

            var clientRule = new ModelClientValidationRule
            {
                ErrorMessage = errorMessage,
                ValidationType = "requiredif",
                ValidationParameters =
                                         {
                                             { "expression", javascriptExpression }
                                         }
            };

            return new[] { clientRule };
        }

    }
}

and call on property like as below:

[RequiredIf("property_name=="prop_value"", ErrorMessageResourceType = typeof(Resources.resfilename), ErrorMessageResourceName = "ErrMessage")]
        public int? propertyname { get; set; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...