Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
737 views
in Technique[技术] by (71.8m points)

c# - RequiredIf required for check validation required on data dataannotations

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

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

1 Reply

0 votes
by (71.8m points)

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; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...