public IEnumerable <ValidationResult> Validate(System.ComponentModel.DataAnnotations.ValidationContext validationContext) { var forumService = (IForumService)validationContext .GetService(typeof(IForumService)); var categoryService = (ICategoryService)validationContext .GetService(typeof(ICategoryService)); var model = validationContext.ObjectInstance as ForumFormInputModel; var categoryResult = categoryService.IsCategoryValid(model.ForumModel.Category); var forumExists = forumService.ForumExists(model.ForumModel.Name); if (forumExists) { yield return(new ValidationResult(ErrorConstants.ForumExistsError)); } if (categoryResult) { yield return(ValidationResult.Success); } else { yield return(new ValidationResult(ErrorConstants.InvalidCategory)); } }
/// <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; }
private static IValidationService GetValidationService(ValidationContext validationContext) { var service = ((IValidationService)validationContext.GetService(typeof(IValidationService))); if (service == null) service = Factories.BuildValidationService(); return service; }
protected override ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { var _repository = (IAgentRepository)validationContext.GetService(typeof(IAgentRepository)); var agent = (Agent)validationContext.ObjectInstance; if (agent.AgentCode == null || agent.AgentName == null) { return(new ValidationResult("Agent code and name are required.")); } return((_repository.Exists(agent)) ? ValidationResult.Success : new ValidationResult("Duplicate agent.")); }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var email = value as String; if (email == null) { throw new ArgumentException("Property type is not String"); } var repository = validationContext.GetService(typeof(IUserRepository)) as IUserRepository; if (repository == null) { throw new InvalidOperationException("Can't access repository"); } var user = AsyncHelper.RunSynchronously(() => repository.GetUserByEmail(email)); if (user != null) { return new ValidationResult(String.Format("This email '{0}' has taken by another user", email), new [] {validationContext.DisplayName}); } return null; }
public static ValidationResult IsValidLocation(string location, ValidationContext validationContext) { if (!string.IsNullOrEmpty(location)) { var meetingData = validationContext.GetService(typeof(IMeetingDataProvider)) as IMeetingDataProvider; if (meetingData != null) { if (!meetingData.Locations.Any(l => l.LocationName == location)) { return new ValidationResult( "That is not a valid location", new[] { validationContext.MemberName }); } } } return ValidationResult.Success; }
public void AdaptShouldReturnValidationContextAdapter() { // arrange var instance = new object(); var service = new object(); var serviceProvider = new ServiceContainer(); var items = new Dictionary<object, object>() { { "Test", "Test" } }; var expected = new ValidationContext( instance, serviceProvider, items ); expected.MemberName = "Foo"; serviceProvider.AddService( typeof( object ), service ); // act var actual = expected.Adapt(); // assert Assert.Equal( expected.DisplayName, actual.DisplayName ); Assert.Same( expected.Items["Test"], actual.Items["Test"] ); Assert.Equal( expected.MemberName, actual.MemberName ); Assert.Same( expected.ObjectInstance, actual.ObjectInstance ); Assert.Equal( expected.ObjectType, actual.ObjectType ); Assert.Same( expected.GetService( typeof( object ) ), actual.GetService( typeof( object ) ) ); }
/// <summary> /// 現在の検証属性に対して、指定した値を検証します。 /// </summary> /// <param name="value">検証対象の値。</param> /// <param name="validationContext">検証操作に関するコンテキスト情報。</param> /// <returns> /// <see cref="T:System.ComponentModel.DataAnnotations.ValidationResult"/> クラスのインスタンス。 /// </returns> protected override ValidationResult IsValid(object value, ValidationContext validationContext) { validator = validationContext.GetService(typeof(IPersonNameValidator)) as IPersonNameValidator; return base.IsValid(value, validationContext); }
public string FormatErrorMessage(ValidationContext validationContext) { var textLocalizer = (ITextLocalizer?)validationContext.GetService(typeof(ITextLocalizer)) ?? NullTextLocalizer.Instance; return(FormatErrorMessage(validationContext.DisplayName, textLocalizer, validationContext)); }
public static ValidationResult ValidateViewModelName( string value, ValidationContext context ) { Arg.NotNull( context, nameof( context ) ); var model = context.ObjectInstance as ViewItemTemplateWizardViewModel; if ( model == null ) return new ValidationResult( SR.InvalidObjectForValidation.FormatDefault( typeof( ViewItemTemplateWizardViewModel ) ) ); switch ( model.ViewModelOption ) { case 1: { // must have the name of the new view model if ( string.IsNullOrEmpty( value ) ) return new ValidationResult( SR.ViewModelNameUnspecified, new[] { "ViewModelName" } ); var validator = context.GetService<IProjectItemNameValidator>(); // the specified view model name must be unique if ( validator != null && !validator.IsItemNameUnique( value ) ) return new ValidationResult( SR.ViewModelNameNonUnique.FormatDefault( value ), new[] { "ViewModelName" } ); break; } case 2: { // must have a selected view model if ( string.IsNullOrEmpty( value ) ) return new ValidationResult( SR.ExistingViewModelUnspecified, new[] { "ViewModelName" } ); break; } } return ValidationResult.Success; }
/// <summary>Returns the service that provides custom validation.</summary> public static T GetSevice <T>(this ValidationContext validationContext) { Guard.NotNull(validationContext, nameof(validationContext)); return((T)validationContext.GetService(typeof(T))); }
public static ValidationResult PreventDoubleBooking(Meeting meeting, ValidationContext validationContext) { if (validationContext.Items.ContainsKey("AllowOverBooking")) { bool allowOverBooking = (bool)validationContext.Items["AllowOverBooking"]; if (!allowOverBooking) { var meetingData = validationContext.GetService(typeof(IMeetingDataProvider)) as IMeetingDataProvider; if (meetingData != null) { var conflicts = from other in meetingData.Meetings.Except(new[] { meeting }) where other.Location == meeting.Location // Check for conflicts by seeing if the times overlap in any way && ( (other.Start >= meeting.Start && other.Start <= meeting.End) || (meeting.Start >= other.Start && meeting.Start <= other.End) || (other.End >= meeting.Start && other.End <= meeting.End) || (meeting.End >= other.Start && meeting.End <= other.End) ) select other; if (conflicts.Any()) { return new ValidationResult( "The location selected is already booked at this time.", new[] { "Location", "Start", "End" }); } } } } return ValidationResult.Success; }