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


C# DataAnnotations.ValidationContext类代码示例

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


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

示例1: Validate

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            List<ValidationResult> carErrors = new List<ValidationResult>();

            if (Make == null)
            {
                carErrors.Add(new ValidationResult("You must enter a make!", new string[] { "Make" }));
            }
            if (Model == null)
            {
                carErrors.Add(new ValidationResult("You must enter a model!", new string[] { "Model" }));
            }
            if (Year == null) //need to fix the date
            {
                carErrors.Add(new ValidationResult("That was not a valid year!", new string[] { "Year" }));
            }
            else if (Year.Length != 4)
            {
                carErrors.Add(new ValidationResult("That was not a valid year!", new string[] { "Year" }));
            }
            if (Title == null)
            {
                carErrors.Add(new ValidationResult("That was not a valid name!", new string[] { "Title" }));
            }
            if (Price > 1000000 || Price == null)
            {
                carErrors.Add(new ValidationResult("Please provide a realistic price!", new string[] { "Price" }));
            }

            return carErrors;
        }
开发者ID:olso4631,项目名称:OlsonRepo,代码行数:31,代码来源:Car.cs

示例2: IsValid

 /// <summary>
 /// Validates the specified value with respect to the current validation attribute.
 /// </summary>
 /// <param name="value"></param>
 /// <param name="validationContext"></param>
 /// <returns></returns>
 protected override ValidationResult IsValid(object value, ValidationContext validationContext)
 {
     if (value == null)
         return null;
     IEntity entity = (IEntity)validationContext.ObjectInstance;
     dynamic entityContext;
     Type type = validationContext.ObjectType;
     while (type.Assembly.IsDynamic)
         type = type.BaseType;
     entityContext = validationContext.GetService(typeof(IEntityQueryable<>).MakeGenericType(type));
     if (entityContext == null)
         return null;
     if (value is string && IsCaseSensitive)
         value = ((string)value).ToLower();
     ParameterExpression parameter = Expression.Parameter(type);
     Expression left = Expression.NotEqual(Expression.Property(parameter, "Index"), Expression.Constant(entity.Index));
     Expression right;
     if (value is string && IsCaseSensitive)
         right = Expression.Equal(Expression.Call(Expression.Property(parameter, validationContext.MemberName), typeof(string).GetMethod("ToLower")), Expression.Constant(value));
     else
         right = Expression.Equal(Expression.Property(parameter, validationContext.MemberName), Expression.Constant(value));
     Expression expression = Expression.And(left, right);
     expression = Expression.Lambda(typeof(Func<,>).MakeGenericType(type, typeof(bool)), expression, parameter);
     object where = _QWhereMethod.MakeGenericMethod(type).Invoke(null, new[] { entityContext.Query(), expression });
     int count = (int)_QCountMethod.MakeGenericMethod(type).Invoke(null, new[] { where });
     if (count != 0)
         return new ValidationResult(string.Format("{0} can not be {1}, there is a same value in the database.", validationContext.MemberName, value));
     else
         return null;
 }
开发者ID:alexyjian,项目名称:ComBoost,代码行数:36,代码来源:DistinctAttribute.cs

示例3: TryValidateEntity

		/// <summary>
		///     Validates a Entity
		/// </summary>
		/// <exception cref="ValidationException"></exception>
		public Tuple<bool, ICollection<ValidationResult>> TryValidateEntity(object instance)
		{
			var context = new ValidationContext(instance);
			var result = new Collection<ValidationResult>();
			var success = Validator.TryValidateObject(instance, context, result);
			return new Tuple<bool, ICollection<ValidationResult>>(success, result);
		}
开发者ID:JPVenson,项目名称:DataAccess,代码行数:11,代码来源:DbAccessLayerValidation.cs

示例4: IsValid

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            int routeId = (int)validationContext.ObjectType.GetProperty(RouteId).GetValue(validationContext.ObjectInstance, null);
            DateTime depatureDateTime = (DateTime)validationContext.ObjectType.GetProperty(DepatureDateTime).GetValue(validationContext.ObjectInstance, null);

            Route route = _routeLogic.GetRouteById(routeId);

            DateTime compareDateTime;
            if (route.WayStations.Count>0)
            {
                compareDateTime = route.WayStations.Last().ArrivalDateTime;
            }
            else
            {
                compareDateTime = route.StartingStation.DepatureDateTime;
            }

            //if (depatureDateTime > route.StartingStationRoute.DepatureDateTime)
            //{
            //    return ValidationResult.Success;
            //}
            if (depatureDateTime > compareDateTime)
            {
                return ValidationResult.Success;
            }

            return new ValidationResult("Отправление должно быть после начала маршрута и после предыдущих станций");
        }
开发者ID:belush,项目名称:TrainBooking,代码行数:28,代码来源:CorrectDepatureDateAttribute.cs

示例5: GetValidationResultShouldReturnNullIfAllIsValid

 public void GetValidationResultShouldReturnNullIfAllIsValid()
 {
     var context = new ValidationContext(Mother.ValidLogin);
     Repo.Setup(r => r.FindOneBy(It.IsAny<Func<Users.User, bool>>())).Returns(Mother.ValidUser);
     var result = InvokeGetValidationResult(new object[] { Mother.ValidLogin.Email, context });
     Assert.IsNull(result);
 }
开发者ID:r41lblast,项目名称:ndriven-cli,代码行数:7,代码来源:ValidLoginAttributeTest.cs

示例6: ValidateModel

 private IList<ValidationResult> ValidateModel(object model)
 {
     var validationResults = new List<ValidationResult>();
     var ctx = new ValidationContext(model, null, null);
     Validator.TryValidateObject(model, ctx, validationResults, true);
     return validationResults;
 }
开发者ID:Mobrockers,项目名称:ilionx-otap,代码行数:7,代码来源:GebruikerTest.cs

示例7: Validate

 public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
 {
     if (Rating < 2 && ReviewerName.ToLower().StartsWith("scott"))
     {
        yield return new ValidationResult("Sorry, Scott, you can't do this");
     }
 }
开发者ID:PaKowalski,项目名称:OdeToFood,代码行数:7,代码来源:RestaurantReview.cs

示例8: GetValidationResult

 public List<ValidationResult> GetValidationResult()
 {
     ValidationContext context = new ValidationContext(this, null, null);
     List<ValidationResult> result = new List<ValidationResult>();
     Validator.TryValidateObject(this, context, result);
     return result;
 }
开发者ID:jeffersonpereira,项目名称:SisCad,代码行数:7,代码来源:dependente.cs

示例9: IsValid

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var results = new List<ValidationResult>();
            CompositeValidationResult compositeResults = null;

            foreach (var o in (IEnumerable)value)
            {
                var context = new ValidationContext(o, null, null);
                Validator.TryValidateObject(o, context, results, true);

                if (results.Count != 0)
                {
                    if (compositeResults == null)
                        compositeResults = new CompositeValidationResult(String.Format("Validation for '{0}' failed", validationContext.DisplayName));
                    results.ForEach(compositeResults.AddResult);
                    results.Clear();
                }
            }

            if (compositeResults != null)
                throw new ValidationException(string.Format("Validation for '{0}' failed", validationContext.DisplayName),
                    new AggregateException(compositeResults.Results.Select(r => new ValidationException(r.ErrorMessage))));

            return ValidationResult.Success;
        }
开发者ID:alexf2,项目名称:VendingMachine,代码行数:25,代码来源:ValidateCollectionAttribute.cs

示例10: Validate

    public static bool Validate(this object instance, out ICollection<ValidationResult> validationResults)
    {
        var validationContext = new ValidationContext(instance);
        validationResults = new List<ValidationResult>();

        return Validator.TryValidateObject(instance, validationContext, validationResults, true);
    }
开发者ID:vl222cu,项目名称:vt14-2-2-aventyrliga-kontakter,代码行数:7,代码来源:MyValidationExtension.cs

示例11: IsValid

        /// <summary>
        /// Determines whether a specified object is valid. (Overrides <see cref = "ValidationAttribute.IsValid(object)" />)
        /// </summary>
        /// <remarks>
        /// This method returns <c>true</c> if the <paramref name = "value" /> is null.  
        /// It is assumed the <see cref = "RequiredAttribute" /> is used if the value may not be null.
        /// </remarks>
        /// <param name = "value">The object to validate.</param>
        /// <returns><c>true</c> if the value is null or less than or equal to the specified maximum length, otherwise <c>false</c></returns>
        /// <exception cref = "InvalidOperationException">Length is zero or less than negative one.</exception>
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            // Check the lengths for legality
            EnsureLegalLengths();

            var length = 0;
            // Automatically pass if value is null. RequiredAttribute should be used to assert a value is not null.
            if (value == null)
            {
                return ValidationResult.Success;
            }
            else
            {
                var str = value as string;
                if (str != null)
                {
                    length = str.Length;
                }
                else
                {
                    // We expect a cast exception if a non-{string|array} property was passed in.
                    length = ((Array)value).Length;
                }
            }

            return MaxAllowableLength == Length || length <= Length ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(validationContext.MemberName));
        }
开发者ID:slown1,项目名称:PortableDataAnnotations,代码行数:37,代码来源:MaxLengthAttribute.cs

示例12: Validate

 public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
 {
     if (!Card.StartsWith(PrefixString))
         yield return new ValidationResult(Properties.Resources.String_GoMoModel_SnPrefixError, new[] { "prefixString" });
     if (!Card.Length.ToString().Equals(LengthString))
         yield return new ValidationResult(Properties.Resources.String_GoMoModel_SnLengthError, new[] { "lengthString" });
 }
开发者ID:TGHGH,项目名称:MesSolution,代码行数:7,代码来源:GoMoModel.cs

示例13: IsValid

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null) { }
            else
            {
                //if we decide phone is required we need to gen msg for empty value
                //var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                //return new ValidationResult(errorMessage);

                return ValidationResult.Success;

            }

            var phoneNumber = RemoveHyphens(RemoveSpaces(value.ToString()));

            Regex regex = new Regex(expressions);
            Match match = regex.Match(phoneNumber);
            if (match.Success)
            {
                var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                return new ValidationResult(errorMessage);
            }

            return ValidationResult.Success;
        }
开发者ID:RedCamel69,项目名称:BSG,代码行数:25,代码来源:BaseTelephoneValidationAttribute.cs

示例14: IsValid

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            // get a reference to the property this validation depends upon
            var containerType = validationContext.ObjectInstance.GetType();
            var field = containerType.GetProperty(DependentProperty);

            if (field != null)
            {
                // get the value of the dependent property
                var dependentvalue = field.GetValue(validationContext.ObjectInstance, null);

                // compare the value against the target value
                if ((dependentvalue == null && TargetValue == null) ||
                    (dependentvalue != null && ((string) TargetValue).Contains(dependentvalue.ToString())))
                {
                    // match => means we should try validating this field
                    if (!_innerAttribute.IsValid(value))
                        // validation failed - return an error
                        return new ValidationResult(FormatErrorMessage(validationContext.DisplayName),
                            new[] {validationContext.MemberName});
                }
            }

            return ValidationResult.Success;
        }
开发者ID:asomarribasd,项目名称:eisk-asp.net-mvc-5.2,代码行数:25,代码来源:RequiredIfAttribute.cs

示例15: IsValid

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var input = validationContext.ObjectInstance as IdentificationUpdateInput;

            if (input != null)
            {
                if (input.NewSightingIdentification ||
                    (!input.NewSightingIdentification && !string.IsNullOrWhiteSpace(input.SightingId)))
                {
                    if (input.IsCustomIdentification)
                    {
                        if (string.IsNullOrWhiteSpace(input.Kingdom) ||
                            string.IsNullOrWhiteSpace(input.Phylum) ||
                            string.IsNullOrWhiteSpace(input.Class) ||
                            string.IsNullOrWhiteSpace(input.Order) ||
                            string.IsNullOrWhiteSpace(input.Family) ||
                            string.IsNullOrWhiteSpace(input.Genus) ||
                            string.IsNullOrWhiteSpace(input.Species))
                        {
                            return new ValidationResult(ErrorMessageString);
                        }
                    }
                    else
                    {
                        if (string.IsNullOrWhiteSpace(input.Taxonomy))
                        {
                            return new ValidationResult(ErrorMessageString);
                        }
                    }
                }
            }

            return ValidationResult.Success;
        }
开发者ID:Bowerbird,项目名称:bowerbird-web,代码行数:34,代码来源:IdentificationRequiredAttribute.cs


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