當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。