当前位置: 首页>>代码示例>>C#>>正文


C# DataAnnotations.ValidationResult类代码示例

本文整理汇总了C#中System.ComponentModel.DataAnnotations.ValidationResult的典型用法代码示例。如果您正苦于以下问题:C# ValidationResult类的具体用法?C# ValidationResult怎么用?C# ValidationResult使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ValidationResult类属于System.ComponentModel.DataAnnotations命名空间,在下文中一共展示了ValidationResult类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ValueComparisonAttribute

 /// <summary>
 /// Initializes new instance of the <see cref="ValueComparisonAttribute"/> class.
 /// </summary>
 /// <param name="otherProperty">The name of the other property.</param>
 /// <param name="comparison">The <see cref="ValueComparison"/> to perform between values.</param>
 public ValueComparisonAttribute(string propertyName, ValueComparison comparison)
     : base(propertyName)
 {
     this.comparison = comparison;
     this.failure = new ValidationResult(String.Empty);
     this.success = ValidationResult.Success;
 }
开发者ID:swankham,项目名称:Epicoil,代码行数:12,代码来源:ValueComparisonAttribute.cs

示例2: IsValid

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            ValidationResult validationResult = ValidationResult.Success;
            try
            {
                var otherPropertyInfo = validationContext.ObjectType.GetProperty(this.otherPropertyName);
                if (otherPropertyInfo.PropertyType.Equals(new TimeSpan().GetType()))
                {
                    var toValidate = (TimeSpan)value;
                    var referenceProperty = (TimeSpan)otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
                    if (toValidate.CompareTo(referenceProperty) < 1)
                    {
                        validationResult = new ValidationResult(ErrorMessageString);
                    }
                }
                else
                {
                    validationResult = new ValidationResult("An error occurred while validating the property. OtherProperty is not of type DateTime");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return validationResult;
        }
开发者ID:kateEvstratenko,项目名称:Bank,代码行数:27,代码来源:DateGreaterThanAttribute.cs

示例3: IsValid

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            ValidationResult validationResult = ValidationResult.Success;
            try
            {
                var otherPropertyInfo = validationContext.ObjectType.GetProperty(this.otherPropertyName);
                var sum = (double)value;
                var creditId = (int)otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
                using (var scope = CustomDependencyResolver.Resolver.BeginScope())
                {
                    var creditService = scope.GetService(typeof (ICreditService)) as ICreditService;
                    if (creditService == null)
                    {
                        validationResult = new ValidationResult("Cannot resolve ICreditService");
                    }
                    else
                    {
                        var credit = creditService.Get(creditId);
                        if (sum < credit.MinSum || sum > credit.MaxSum)
                        {
                            var errorMessage = String.Format("Sum should be between {0} and {1}.", credit.MinSum,
                                credit.MaxSum);
                            validationResult = new ValidationResult(errorMessage);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return validationResult;
        }
开发者ID:kateEvstratenko,项目名称:Bank,代码行数:34,代码来源:SumRangeAttribute.cs

示例4: Constructor_String_IEnumerable

		public void Constructor_String_IEnumerable ()
		{
			var vr = new ValidationResult ("message", null);

			Assert.AreEqual ("message", vr.ErrorMessage, "#A1");
			Assert.IsNotNull (vr.MemberNames, "#A2-1");

			int count = 0;
			foreach (string m in vr.MemberNames)
				count++;
			Assert.AreEqual (0, count, "#A2-2");

			var names = new string[] { "one", "two" };
			vr = new ValidationResult ("message", names);

			Assert.AreEqual ("message", vr.ErrorMessage, "#A1");
			Assert.IsNotNull (vr.MemberNames, "#A2-1");
			Assert.AreSame (names, vr.MemberNames, "#A2-2");

			count = 0;
			foreach (string m in vr.MemberNames)
				count++;
			Assert.AreEqual (2, count, "#A2-3");

			vr = new ValidationResult (null, null);
			Assert.AreEqual (null, vr.ErrorMessage, "#A3");
		}
开发者ID:nlhepler,项目名称:mono,代码行数:27,代码来源:ValidationResultTest.cs

示例5: IsValid

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var errorMessage = $"The {validationContext.DisplayName} field is required.";
            var validationResult = new ValidationResult(errorMessage, new string[] { validationContext.DisplayName });

            if (value == null) return validationResult;

            if (value is string && string.IsNullOrWhiteSpace(value.ToString()))
            {
                return validationResult;
            }

            var incoming = value.ToString();

            decimal val = 0;
            if (Decimal.TryParse(incoming, out val) && val == 0)
            {
                return validationResult;
            }

            var date = DateTime.MinValue;
            if (DateTime.TryParse(incoming, out date) && date == DateTime.MinValue)
            {
                return validationResult;
            }

            return ValidationResult.Success;
        }
开发者ID:randydotnet,项目名称:Peasy.NET,代码行数:28,代码来源:PeasyRequiredAttribute.cs

示例6: Validate

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var failedValidationResult = new ValidationResult("An error occured!");
            var failedResult = new[] { failedValidationResult };

            if (!string.IsNullOrEmpty(this.Honeypot))
            {
                return failedResult;
            }

            DateTime timestamp;

            if (!DateTime.TryParseExact(this.Timestamp, "ffffMMHHyytssmmdd",
                                null, DateTimeStyles.None, out timestamp))
            {
                return failedResult;
            }

            if (DateTime.Now.AddMinutes(-5) > timestamp)
            {
                return failedResult;
            }

            return new[] { ValidationResult.Success };
        }
开发者ID:joelwahlund81,项目名称:MoonAid,代码行数:25,代码来源:RegisterViewModel.cs

示例7: Validate

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var validationResults = new HashSet<ValidationResult>();

            var contest = this.data.Contests.GetById(this.ContestId);
            var contestQuestions = contest.Questions
                .Where(x => !x.IsDeleted)
                .ToList();

            var counter = 0;
            foreach (var question in contestQuestions)
            {
                var answer = this.Questions.FirstOrDefault(x => x.QuestionId == question.Id);
                var memberName = string.Format("Questions[{0}].Answer", counter);
                if (answer == null)
                {
                    var validationErrorMessage = string.Format(Resource.Question_not_answered, question.Id);
                    var validationResult = new ValidationResult(validationErrorMessage, new[] { memberName });
                    validationResults.Add(validationResult);
                }
                else if (!string.IsNullOrWhiteSpace(question.RegularExpressionValidation) && !Regex.IsMatch(answer.Answer, question.RegularExpressionValidation))
                {
                    var validationErrorMessage = string.Format(Resource.Question_not_answered_correctly, question.Id);
                    var validationResult = new ValidationResult(validationErrorMessage, new[] { memberName });
                    validationResults.Add(validationResult);
                }

                counter++;
            }

            return validationResults;
        }
开发者ID:Dimitvp,项目名称:OpenJudgeSystem,代码行数:32,代码来源:ContestRegistrationModel.cs

示例8: IsValid

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            ValidationResult validationResult = new ValidationResult("\"" + value.ToString() + "\"" + ErrorMessageString);
            try
            {
                if (value is string)
                {
                    string frequencyString = (string)value;
                    if (frequencyString.Equals("hourly"))
                        validationResult = ValidationResult.Success;
                    if (frequencyString.Equals("daily"))
                        validationResult = ValidationResult.Success;
                    if (frequencyString.Equals("weekly"))
                        validationResult = ValidationResult.Success;
                    if (frequencyString.Equals("monthly"))
                        validationResult = ValidationResult.Success;
                    if (frequencyString.Equals("yearly"))
                        validationResult = ValidationResult.Success;
                }
                else
                {
                    validationResult = new ValidationResult("An error occurred while validating the property. OtherProperty is not of type String");
                }
            }
            catch (Exception ex)
            {
                // Do stuff, i.e. log the exception
                // Let it go through the upper levels, something bad happened
                throw ex;
            }

            return validationResult;
        }
开发者ID:peelol,项目名称:HealthAppSprint2b,代码行数:33,代码来源:CustomTaskValidationAttributes.cs

示例9: Validate

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var validationResults = new HashSet<ValidationResult>();

            var contest = this.regData.CustomerCards.GetById(this.ContestId);
            var contestQuestions = contest.Questions.ToList();

            var counter = 0;
            foreach (var question in contestQuestions)
            {
                var answer = this.Questions.FirstOrDefault(x => x.QuestionId == question.Id);
                var memberName = string.Format("Questions[{0}].Answer", counter);
                if (answer == null)
                {
                    var validationErrorMessage = string.Format("Question with id {0} was not answered.", question.Id);
                    var validationResult = new ValidationResult(validationErrorMessage, new[] { memberName });
                    validationResults.Add(validationResult);
                }
                else if (!string.IsNullOrWhiteSpace(question.RegularExpressionValidation) &&
                         !Regex.IsMatch(answer.Answer, question.RegularExpressionValidation))
                {
                    var validationErrorMessage = string.Format(
                        "Question with id {0} is not in the correct format.", question.Id);
                    var validationResult = new ValidationResult(validationErrorMessage, new[] { memberName });
                    validationResults.Add(validationResult);
                }

                counter++;
            }

            return validationResults;
        }
开发者ID:sworn87,项目名称:TechSupportWebApi,代码行数:32,代码来源:CustomerCardRegistrationModel.cs

示例10: IsValid

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            ValidationResult validationResult = ValidationResult.Success;
            string pw = value.ToString();

            bool num = false;
            bool letter = false;
            foreach (char c in pw)
            {
                if (Char.IsDigit(c))
                {
                    num = true;
                }
                else
                {
                    if (Char.IsLetter(c))
                    {
                        letter = true;
                    }
                }
            }
            if (!num || !letter)
            {
                validationResult = new ValidationResult(ErrorMessageString);
            }
            return validationResult;
        }
开发者ID:OzzieSoft,项目名称:SrPrjGrp2,代码行数:27,代码来源:AccountModels.cs

示例11: Can_construct_get_and_set_ErrorMessage

 public static void Can_construct_get_and_set_ErrorMessage()
 {
     var validationResult = new ValidationResult("SomeErrorMessage");
     Assert.Equal("SomeErrorMessage", validationResult.ErrorMessage);
     validationResult.ErrorMessage = "SomeOtherErrorMessage";
     Assert.Equal("SomeOtherErrorMessage", validationResult.ErrorMessage);
 }
开发者ID:noahfalk,项目名称:corefx,代码行数:7,代码来源:ValidationResultTests.cs

示例12: IsValid

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            ValidationResult validationResult = ValidationResult.Success; 
            try
            {
                // Using reflection we can get a reference to the other date property, in this example the project start date
                var otherPropertyInfo = validationContext.ObjectType.GetProperty(this.otherPropertyName);                
                // Let's check that otherProperty is of type DateTime as we expect it to be
                if (otherPropertyInfo.PropertyType.Equals(new DateTime().GetType()))
                {
                    DateTime toValidate = (DateTime)value;
                    DateTime referenceProperty = (DateTime)otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);                    
                    // if the end date is lower than the start date, than the validationResult will be set to false and return
                    // a properly formatted error message
                    if (toValidate.CompareTo(referenceProperty) < 1)
                    {
                        //string message = FormatErrorMessage(validationContext.DisplayName);
                        //validationResult = new ValidationResult(message);
                        validationResult = new ValidationResult(ErrorMessageString);
                    }
                }
                else
                {
                    validationResult = new ValidationResult("An error occurred while validating the property. OtherProperty is not of type DateTime");
                }
            }
            catch (Exception ex)
            {
                // Do stuff, i.e. log the exception
                // Let it go through the upper levels, something bad happened
                throw ex;
            }

            return validationResult;
        }
开发者ID:RingoKam,项目名称:DateCustomValidationExample,代码行数:35,代码来源:DateGreaterThanAttribute.cs

示例13: ValidateAttributes

        private static IEnumerable<ValidationResult> ValidateAttributes(object instance,
            ValidationContext validationContext,
            string prefix)
        {
            PropertyDescriptor[] propertyDescriptorCollection =
                TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>().ToArray();

            IEnumerable<ValidationResult> valResults = propertyDescriptorCollection.SelectMany(
                prop => prop.Attributes.OfType<ValidationAttribute>(), (prop, attribute) =>
                {
                    validationContext.DisplayName = prop.Name;
                    ValidationResult validationresult = attribute.GetValidationResult(prop.GetValue(instance),
                        validationContext);
                    if (validationresult != null)
                    {
                        IEnumerable<string> memberNames = validationresult.MemberNames.Any()
                            ? validationresult.MemberNames.Select(c => prefix + c)
                            : new[] { prefix + prop.Name };
                        validationresult = new ValidationResult(validationresult.ErrorMessage, memberNames);
                    }
                    return validationresult;
                })
                .Where(
                    validationResult =>
                        validationResult !=
                        ValidationResult.Success);
            return
                valResults;
        }
开发者ID:jorik041,项目名称:Tools-1,代码行数:29,代码来源:ObjectValidator.cs

示例14: ValidationResult

        /// <summary>
        /// Constructor that creates a copy of an existing ValidationResult.
        /// </summary>
        /// <param name="validationResult">The validation result.</param>
        /// <exception cref="System.ArgumentNullException">The <paramref name="validationResult"/> is null.</exception>
        protected ValidationResult(ValidationResult validationResult) {
            if (validationResult == null) {
                throw new ArgumentNullException("validationResult");
            }

            this._errorMessage = validationResult._errorMessage;
            this._memberNames = validationResult._memberNames;
        }
开发者ID:kvervo,项目名称:HorizontalLoopingSelector,代码行数:13,代码来源:ValidationResult.cs

示例15: ValidationResult

        /// <summary>
        /// Initializes a new instance of the <see cref="T:System.ComponentModel.DataAnnotations.ValidationResult" /> class by
        /// using a <see cref="T:System.ComponentModel.DataAnnotations.ValidationResult" /> object.
        /// </summary>
        /// <param name="validationResult">The validation result object.</param>
        protected ValidationResult( ValidationResult validationResult )
        {
            if ( validationResult == null )
                throw new ArgumentNullException( "validationResult" );

            ErrorMessage = validationResult.ErrorMessage;
            memberNames = validationResult.memberNames;
        }
开发者ID:WaffleSquirrel,项目名称:More,代码行数:13,代码来源:ValidationResult.cs


注:本文中的System.ComponentModel.DataAnnotations.ValidationResult类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。