Esempio n. 1
2
        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;
        }
        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("Отправление должно быть после начала маршрута и после предыдущих станций");
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (CustomValidators.IsLogicalDelete(validationContext))
            {
                return ValidationResult.Success;
            }

            var dynamicObject = CustomValidators.GetEntity(validationContext.ObjectInstance);
            if (dynamicObject.EntityState.ToString() == "Detached")
            {
                return ValidationResult.Success;
            }
            if (value is IEnumerable)
            {
                foreach (var element in (IEnumerable)value)
                {
                    return ValidationResult.Success;
                }
            }

            List<string> members = new List<string>() { validationContext.MemberName };
            List<string> linkedMembers = CustomValidators.GetLinkedMembers(validationContext);
            if (linkedMembers.Any())
            {
                members.AddRange(linkedMembers);
            }

            return new ValidationResult(this.ErrorMessage , members);
        }
 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);
 }
        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;
        }
Esempio n. 6
0
 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;
 }
Esempio n. 7
0
 public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
 {
     if (AntiSpamAnswer != "4")
     {
         yield return new ValidationResult("Введите правильный ответ", new string[] {"AntiSpamAnswer"});
     }
 }
        public void UiDateTimeDateValidationFails()
        {
            _timeZoneName = TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time").StandardName;
            var model = new ValidationTestUiDateTimeModel
                                        {
                                            BasicDateTime = new UiDateTimeModel(_timeZoneName)
                                                                        {
                                                                            LocalDate = "1/15/"
                                                                        }
                                        };
            var testContext = new ValidationContext(model, null, null) { DisplayName = "BasicDateTime" };
            var attribute = new UiDateTimeFormatDateValidation("LocalDate");

            try
            {
                attribute.Validate(model.BasicDateTime.LocalDate, testContext);
                Assert.Fail("Exception not thrown");
            }
            catch (ValidationException ex)
            {
                Assert.AreEqual("'Date' does not exist or is improperly formated: MM/DD/YYYY.", ex.Message);
            }
            catch (Exception)
            {
                Assert.Fail("Unexpected Exception thrown");
            }
        }
Esempio n. 9
0
        protected override ValidationResult IsValid(object value, ValidationContext context)
        {
            var fileEntity = value as FileEntity;
            if (fileEntity == null)
            {
                return ValidationResult.Success;
            }

            try
            {
                using (FileStream fileStream = File.OpenRead(fileEntity.Uri))
                {
                    if (fileStream.Length > 0)
                    {
                        var buffer = new byte[HeaderLength];
                        int readed = fileStream.Read(buffer, 0, buffer.Length);
                        string fileHeader = Encoding.UTF8.GetString(buffer, 0, readed);

                        if (fileHeader.ToLowerInvariant().Contains(@"<avsx"))
                        {
                            return ValidationResult.Success;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Trace.TraceError("Failed to receive file information: {0}", e);
            }

            return new ValidationResult(FormatErrorMessage(context.DisplayName));
        }
Esempio n. 10
0
 public static IList<ValidationResult> Validate(object modelToValidate)
 {
     var results = new List<ValidationResult>();
     var validationContext = new ValidationContext(modelToValidate);
     Validator.TryValidateObject(modelToValidate, validationContext, results, true);
     return results;
 }
		/// <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);
		}
 public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
 {
     if (!LocationService.IsValidMakeForRegion(Vehicle.Make, Dealer.Location))
     {
         yield return new ValidationResult("Make is invalid for region.");
     }
 }
 public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
 {
     if (Values == null || Values.Count <= 0)
     {
         yield return new ValidationResult("需要至少设置一个属性");
     }
 }
Esempio n. 14
0
        public void IsValid_EqualValue()
        {
            AttributesModel model = new AttributesModel();
            ValidationContext context = new ValidationContext(model);

            Assert.Null(attribute.GetValidationResult(model.Sum, context));
        }
        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;
        }
        /// <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));
        }
        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;
        }
        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;
        }
		/// <summary>
		///     Validates a Entity
		/// </summary>
		/// <exception cref="ValidationException"></exception>
		public void ValidateEntityPk(object instance)
		{
			var pkProperty = this.GetClassInfo(instance.GetType()).PrimaryKeyProperty.PropertyName;
			var context = new ValidationContext(instance);
			context.MemberName = pkProperty;
			Validator.ValidateProperty(instance, context);
		}
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var numericProperty = validationContext.ObjectType.GetProperty(this.NumericPropertyName);
            
            // Check that number property is not null.
            if (numericProperty == null)
            {
                return new ValidationResult(String.Format("Unknown property: {0}.", this.NumericPropertyName));
            }

            // Get the number property value.
            var numericValue = (int)numericProperty.GetValue(validationContext.ObjectInstance, null);

            // Check string property type.
            if (validationContext.ObjectType.GetProperty(validationContext.MemberName).PropertyType != "".GetType())
            {
                return new ValidationResult(String.Format("The type of {0} must be string.",
                    validationContext.DisplayName));
            }

            // Check if the user has entered an adjustment.
            if (numericValue < FloorValue || numericValue > CeilingValue)
            {
                // Check if the user has entered an adjustment explanation.
                if (Convert.ToString(value).Length < this.MinimumNoteLength)
                {
                    return new ValidationResult(
                        String.Format(ValidationMessage));
                }
            }

            // Property is valid.
            return null;
        }
Esempio n. 21
0
 public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
 {
     if (Rating < 2 && ReviewerName.ToLower().StartsWith("scott"))
     {
        yield return new ValidationResult("Sorry, Scott, you can't do this");
     }
 }
Esempio n. 22
0
 /// <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;
 }
		/// <summary>
		/// Validates the specified value with respect to the current validation attribute.
		/// </summary>
		/// <param name="value">
		/// The value to validate.
		/// </param>
		/// <param name="validationContext">
		/// The context information about the validation operation.
		/// </param>
		/// <returns>
		/// An instance of the <see cref="T:System.ComponentModel.DataAnnotations.ValidationResult"/> class.
		/// </returns>
		protected override ValidationResult PerformCustomValidation(object value, ValidationContext validationContext)
		{
			if (value.IsNull())
			{
				return ValidationResult.Success;
			}

			if (validationContext.IsNull())
			{
				validationContext = new ValidationContext(value, null, null) { DisplayName = "The value" };
			}

			var memberNames = new[] { validationContext.MemberName };

			int length = value.ToString().Length;

			if (length > this.maximumLength)
			{
				this.ErrorMessage = string.Format(ValidationMessages.ValueGreaterThanMaximumLength, validationContext.DisplayName, this.maximumLength);

				return new ValidationResult(this.ErrorMessage, memberNames);
			}

			return ValidationResult.Success;
		}
    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);
    }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            string valueString = "";
            try
            {
                valueString = (string)value;
            }
            catch (Exception)
            {
                return new ValidationResult("Property is invalid");
            }
            if (string.IsNullOrEmpty(valueString))
            {
                return ValidationResult.Success;
            }

            using (edisDbEntities db = new edisDbEntities())
            {
                var clientGroup = db.ClientGroups.SingleOrDefault(s => s.ClientGroupId == valueString);
                if (clientGroup != null)
                {
                    return ValidationResult.Success;
                }
                else
                {
                    return new ValidationResult(ErrorMessage);
                }
            }
        }
        protected override ValidationResult IsValid(object value, ValidationContext obj) {
            if (value == null) {
                return ValidationResult.Success;
            }

            var propertyInfo = obj.ObjectInstance.GetType().GetProperty(this.propertyName);

            if (propertyInfo == null) {
                // Should actually throw an exception.
                return ValidationResult.Success;
            }

            dynamic otherValue = propertyInfo.GetValue(obj.ObjectInstance);

            if (otherValue == null) {
                return ValidationResult.Success;
            }

            // Unfortunately we have to use the DateTime type here.
            //var compare = ((IComparable<DateTime>)otherValue).CompareTo((DateTime)value);
            var compare = otherValue.CompareTo((DateTime)value);

            if (compare >= 0) {
                return new ValidationResult(this.ErrorMessage);
            }

            return ValidationResult.Success;
        }
Esempio n. 27
0
 public List<ValidationResult> GetValidationResult()
 {
     ValidationContext context = new ValidationContext(this, null, null);
     List<ValidationResult> result = new List<ValidationResult>();
     Validator.TryValidateObject(this, context, result);
     return result;
 }
Esempio n. 28
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {

            string wielkosc;
          

            if (value is string)
            {
                wielkosc = value.ToString();
            }
            else return new ValidationResult("Te pole nie powinno być puste");

            if (wielkosc.Length == 0)
                return new ValidationResult("Te pole nie powinno być puste");
            else
                wielkosc = value.ToString();

            if (wielkosc.Length < 3 || wielkosc.Length > 40)
                return new ValidationResult("Te pole powinno zawierać między 3 a 40 znaków");
            else
                wielkosc = value.ToString();


            return ValidationResult.Success;
        }
Esempio n. 29
0
 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" });
 }
Esempio n. 30
0
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (Name.Contains("-") || Name.Contains("+"))
            {
                yield return new ValidationResult("Name cannot have the characters '-' or '+'.", new[] { "Title" });
            }

            if (string.IsNullOrWhiteSpace(Name) || Name.Length > 15)
            {
                yield return new ValidationResult("Name cannot be empty, all whitespaces or longer than 15 characters.", new[] { "Name" });
            }

            if (!string.IsNullOrWhiteSpace(Email))
            {
                const string emailRegex = @"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*"
                                        + "@"
                                        + @"((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$";

                var re = new Regex(emailRegex);
                var match = re.Match(Email);

                if (!match.Success)
                {
                    yield return new ValidationResult("Email is not valid.", new[] { "Email" });
                }
            }
        }
        public static bool IsValid(object obj)
        {
            var  context = new System.ComponentModel.DataAnnotations.ValidationContext(obj, serviceProvider: null, items: null);
            var  results = new List <ValidationResult>();
            bool isValid = Validator.TryValidateObject(obj, context, results, true);

            return(isValid);
        }
Esempio n. 32
0
        /// <summary>
        /// Kontrola validace modelu
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static IList <ValidationResult> ValidateModel(object model)
        {
            var validationResults = new List <ValidationResult>();
            var ctx = new System.ComponentModel.DataAnnotations.ValidationContext(model, null, null);

            Validator.TryValidateObject(model, ctx, validationResults, true);
            return(validationResults);
        }
Esempio n. 33
0
        private static bool IsValid(object obj)
        {
            var validationContext = new ValidationContext(obj);

            var validationResults = new List <ValidationResult>();

            return(Validator.TryValidateObject(obj, validationContext, validationResults, true));
        }
Esempio n. 34
0
        private ServiceValidationException GetServiceValidationExeption()
        {
            Mock <IServiceProvider> serviceProvider   = new Mock <IServiceProvider>();
            List <ValidationResult> validationResults = new List <ValidationResult>();

            System.ComponentModel.DataAnnotations.ValidationContext validationContext = new System.ComponentModel.DataAnnotations.ValidationContext(this.viewModel, serviceProvider.Object, null);
            return(new ServiceValidationException(validationContext, validationResults));
        }
        private static bool IsValid(object dto)
        {
            //1:00:18
            var validationContext = new ValidationContext(dto);
            var validationResult  = new List <ValidationResult>();

            return(Validator.TryValidateObject(dto, validationContext, validationResult, true));
        }
Esempio n. 36
0
        private static bool IsValid(object obj)
        {
            var validationContext = new System.ComponentModel.DataAnnotations.ValidationContext(obj);

            var validationResult = new List <ValidationResult>();

            return(Validator.TryValidateObject(obj, validationContext, validationResult, true));
        }
        private static bool IsValid(object entity)
        {
            ValidationContext validationContext = new ValidationContext(entity);
            var validationResult = new List <ValidationResult>();

            return(Validator.TryValidateObject(
                       entity, validationContext, validationResult, true));
        }
Esempio n. 38
0
        protected ServiceValidationException GetServiceValidationException()
        {
            var serviceProvider   = new Mock <IServiceProvider>();
            var validationResults = new List <ValidationResult>();

            System.ComponentModel.DataAnnotations.ValidationContext validationContext = new System.ComponentModel.DataAnnotations.ValidationContext(formDto, serviceProvider.Object, null);
            return(new ServiceValidationException(validationContext, validationResults));
        }
Esempio n. 39
0
        private static 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);
        }
        public static bool IsValid(object obj)
        {
            var validationContext = new System.ComponentModel.DataAnnotations.ValidationContext(obj);
            var validationResults = new List <ValidationResult>();
            var isValid           = Validator.TryValidateObject(obj, validationContext, validationResults, true);

            return(isValid);
        }
Esempio n. 41
0
        private IList <ValidationResult> ValidateModel(object model)
        {
            var validationContext = new System.ComponentModel.DataAnnotations.ValidationContext(model, null, null);
            var results           = new List <ValidationResult>();

            Validator.TryValidateObject(model, validationContext, results, true);
            return(results);
        }
        public void CallPostedToByteArrayMethodOfFileConverter_WhenModelStateIsValidAndThereAreFilesInTheRequest()
        {
            // Arrange
            var userServiceMock   = new Mock <IUserService>();
            var fileConverterMock = new Mock <IFileConverter>();
            var mapperMock        = new Mock <IMapper>();

            var userViewModel = new UserDetailsViewModel()
            {
                FirstName = "Ivan",
                LastName  = "Stanev",
                Email     = "Email",
                Gender    = Gender.Male
            };

            var userDbModel = new User()
            {
                FirstName = userViewModel.FirstName,
                LastName  = userViewModel.LastName,
                Email     = userViewModel.Email,
                Gender    = userViewModel.Gender
            };

            var validationContext =
                new System.ComponentModel.DataAnnotations.ValidationContext(userViewModel, null, null);

            var results = new List <ValidationResult>();

            var isModelValid = Validator.TryValidateObject(userViewModel, validationContext, results);

            mapperMock.Setup(x => x.Map <User>(userViewModel)).Returns(userDbModel);

            var userController =
                new UserController(userServiceMock.Object, fileConverterMock.Object, mapperMock.Object);

            var contextMock  = new Mock <HttpContextBase>();
            var identityMock = new Mock <IIdentity>();
            var requestMock  = new Mock <HttpRequestBase>();
            var filesMock    = new Mock <HttpFileCollectionBase>();
            var pictureMock  = new Mock <HttpPostedFileBase>();

            contextMock.Setup(c => c.Request).Returns(requestMock.Object);
            contextMock.Setup(c => c.User.Identity).Returns(identityMock.Object);
            identityMock.Setup(i => i.Name).Returns(It.IsAny <string>());
            pictureMock.Setup(p => p.ContentLength).Returns(1);
            filesMock.Setup(f => f.Count).Returns(1);
            filesMock.Setup(f => f["ProfilePicture"]).Returns(pictureMock.Object);
            requestMock.Setup(r => r.Files).Returns(filesMock.Object);
            userController.ControllerContext =
                new ControllerContext(contextMock.Object, new RouteData(), userController);

            // Act
            userController.EditUser(userViewModel);

            // Assert
            Assert.IsTrue(isModelValid);
            fileConverterMock.Verify(fcm => fcm.PostedToByteArray(pictureMock.Object), Times.Once);
        }
        private static bool IsValid(object entity)
        {
            var context = new System.ComponentModel.DataAnnotations.ValidationContext(entity);
            var results = new List <ValidationResult>();

            bool isValid = Validator.TryValidateObject(entity, context, results, true);

            return(isValid);
        }
        public IEnumerable <ValidationResult> Validate(System.ComponentModel.DataAnnotations.ValidationContext validationContext)
        {
            var distinctedIngredientIds = this.Ingredients.Select(x => x.IngredientId).Distinct().ToList();

            if (distinctedIngredientIds.Count != this.Ingredients.Count)
            {
                yield return(new ValidationResult("You can choose specific ingredient only once."));
            }
        }
Esempio n. 45
0
 public IEnumerable<ValidationResult> Validate(System.ComponentModel.DataAnnotations.ValidationContext validationContext)
 {
     return this.Rules<AnswerFormModel>(v =>
     {
         v.RuleFor(m => m.AnswerText).NotEmpty().WithMessage("Treść jest wymagana");
         v.RuleFor(m => m.IsCorrect).NotEmpty().WithMessage("Określenie poprawności jest wymagane");
     })
     .Validate(this).Result();
 }
        public static bool IsValid(object obj)
        {
            ValidationContext validationContext = new ValidationContext(obj);
            var validationResults = new List <ValidationResult>();

            var result = Validator.TryValidateObject(obj, validationContext, validationResults, true);

            return(result);
        }
Esempio n. 47
0
        private static bool IsValid(object entity)
        {
            ValidationContext       validationContext = new ValidationContext(entity);
            List <ValidationResult> validationResults = new List <ValidationResult>();

            bool result = Validator.TryValidateObject(entity, validationContext, validationResults, true);

            return(result);
        }
Esempio n. 48
0
        public IEnumerable <da.ValidationResult> Validate(da.ValidationContext validationContext)
        {
            var validator = new ForecastValidator(this);
            var result    = validator.Validate(this);

            return(result.Errors.Select(error =>
                                        new da.ValidationResult(PrependProcessStatusToString(error.ErrorMessage, ProcessStatus.Warning),
                                                                new [] { error.PropertyName })));
        }
Esempio n. 49
0
        public static List <ValidationResult> Validate(this IRequest obj)
        {
            var context =
                new System.ComponentModel.DataAnnotations.ValidationContext(obj, serviceProvider: null, items: null);
            var validationResults = new List <ValidationResult>();
            var isValid           = Validator.TryValidateObject(obj, context, validationResults, true);

            return(validationResults);
        }
Esempio n. 50
0
 public IEnumerable <ValidationResult> Validate(System.ComponentModel.DataAnnotations.ValidationContext validationContext)
 {
     return(this.Rules <QuizFormModel>(v =>
     {
         v.RuleFor(m => m.Name).NotEmpty().WithMessage("Nazwa jest wymagana");
         v.RuleFor(m => m.Questions).NotEmpty().WithMessage("Pytania są wymagane");
     })
            .Validate(this).Result());
 }
Esempio n. 51
0
        public static bool IsValid(object obj)
        {
            var validationContext = new DataAnotations.ValidationContext(obj);
            var validationsResult = new List <DataAnotations.ValidationResult>();

            var result = DataAnotations.Validator.TryValidateObject(obj, validationContext, validationsResult, true);

            return(result);
        }
Esempio n. 52
0
        private static bool IsValid(object obj)
        {
            System.ComponentModel.DataAnnotations.ValidationContext validationContext = new System.ComponentModel.DataAnnotations.ValidationContext(obj);
            List <ValidationResult> results = new List <ValidationResult>();

            bool isValid = Validator.TryValidateObject(obj, validationContext, results, true);

            return(isValid);
        }
        private static bool IsValid(object entity)
        {
            System.ComponentModel.DataAnnotations.ValidationContext validatorContext = new System.ComponentModel.DataAnnotations.ValidationContext(entity);
            IList <ValidationResult> validationResult = new List <ValidationResult>();

            bool isValid = Validator.TryValidateObject(entity, validatorContext, validationResult, true);

            return(isValid);
        }
Esempio n. 54
0
        private static bool IsValid(object obj)
        {
            var context = new Annotations.ValidationContext(obj);
            var results = new List <Annotations.ValidationResult>();

            var isValid = Annotations.Validator.TryValidateObject(obj, context, results, true);

            return(isValid);
        }
        public static ValidationResult ValidateEmail(string email, System.ComponentModel.DataAnnotations.ValidationContext context)
        {
            if (!string.IsNullOrWhiteSpace(email) && _regex.IsMatch(email))
            {
                return(ValidationResult.Success);
            }

            return(new ValidationResult("Invalid email format"));
        }
Esempio n. 56
0
        private static bool isValid(object obj)
        {
            var validator     = new System.ComponentModel.DataAnnotations.ValidationContext(obj);
            var validationRes = new List <ValidationResult>();

            var res = Validator.TryValidateObject(obj, validator, validationRes, validateAllProperties: true);

            return(res);
        }
        protected override ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext)
        {
            if (!IsCNPJValid((string)value))
            {
                return(new ValidationResult("CNPJ inválido"));
            }

            return(ValidationResult.Success);
        }
Esempio n. 58
0
        public virtual async void Should_Success_Validate_data()
        {
            var dbContext        = DbContext(GetCurrentMethod());
            var iserviceProvider = GetServiceProviderMock(dbContext).Object;
            Mock <IServiceProvider> serviceProvider = new Mock <IServiceProvider>();

            serviceProvider.
            Setup(x => x.GetService(typeof(SalesDbContext)))
            .Returns(dbContext);

            GarmentBookingOrderFacade facade = new GarmentBookingOrderFacade(serviceProvider.Object, dbContext);

            var data = await DataUtil(facade, dbContext).GetNewData();

            var date = DateTime.Now.AddMonths(1);

            data.DeliveryDate = new DateTime(date.Year, date.Month, 23);


            GarmentBookingOrderViewModel vm = new GarmentBookingOrderViewModel
            {
                BookingOrderNo   = data.BookingOrderNo,
                BookingOrderDate = data.BookingOrderDate,
                DeliveryDate     = data.DeliveryDate,
                Items            = new List <GarmentBookingOrderItemViewModel> {
                    new GarmentBookingOrderItemViewModel
                    {
                        DeliveryDate = data.DeliveryDate,
                    },
                    new GarmentBookingOrderItemViewModel
                    {
                        DeliveryDate = data.DeliveryDate.AddDays(-20),
                    }
                }
            };

            System.ComponentModel.DataAnnotations.ValidationContext validationContext1 = new System.ComponentModel.DataAnnotations.ValidationContext(vm, serviceProvider.Object, null);
            var validationResultCreate1 = vm.Validate(validationContext1).ToList();

            Assert.True(validationResultCreate1.Count() > 0);

            //data.DeliveryDate = new DateTime(date.Year, date.Month, 3);


            GarmentBookingOrderViewModel vm1 = new GarmentBookingOrderViewModel
            {
                BookingOrderNo   = data.BookingOrderNo,
                BookingOrderDate = data.BookingOrderDate,
                DeliveryDate     = new DateTime(date.Year, date.Month, 3),
            };

            System.ComponentModel.DataAnnotations.ValidationContext validationContext = new System.ComponentModel.DataAnnotations.ValidationContext(vm1, serviceProvider.Object, null);
            var validationResultCreate = vm1.Validate(validationContext).ToList();

            Assert.True(validationResultCreate.Count() > 0);
        }
Esempio n. 59
0
        public static bool IsValid(object @object, bool validateAllProperties = true)
        {
            ICollection <ValidationResult> validations = new List <ValidationResult>();

            var validationContext = new System.ComponentModel.DataAnnotations.ValidationContext(@object);

            bool isValid = Validator.TryValidateObject(@object, validationContext, validations, validateAllProperties: validateAllProperties);

            return(isValid);
        }
        private static bool IsValid(object obj)
        {
            // what this method does is basically goes to each property and check data anotations
            var validationContext = new System.ComponentModel.DataAnnotations.ValidationContext(obj);
            List <ValidationResult> validationResults = new List <ValidationResult>();

            Boolean isValid = Validator.TryValidateObject(obj, validationContext, validationResults, true);

            return(isValid);
        }