Example #1
0
        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;
        }
        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;
        }
        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;
        }
Example #4
0
 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);
 }
        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;
        }
        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;
        }
        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;
        }
        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 };
        }
Example #9
0
        // ******************************************************************
        /// <summary>
        /// Calling with null will remove any existing errors if any.
        /// </summary>
        /// <param name="propertyName"></param>
        /// <param name="validationResults"></param>
        public void SetErrorFor <T>(Expression <Func <T> > property, ValidationResult validationResult = null)
        {
            var asMember = property.Body as MemberExpression;

            if (asMember == null)
            {
                throw new ArgumentException("Unable to find property name.");
            }

            string propertyName = asMember.Member.Name;

            if (validationResult == null || validationResult.ErrorMessage == null)
            {
                // Remove the existing errors for this property
                List <string> fakeListForRemoval;
                if (_errors.TryRemove(propertyName, out fakeListForRemoval))
                {
                    OnErrorsChanged(propertyName);
                }
            }
            else
            {
                // Add or Update
                var errorList = new List <string>(1);
                errorList.Add(validationResult.ErrorMessage);
                _errors[propertyName] = errorList;
                OnErrorsChanged(propertyName);
            }
        }
Example #10
0
		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");
		}
Example #11
0
        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;
        }
        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;
        }
        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;
        }
 /// <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;
 }
Example #15
0
            public void It_should_succeed()
            {
                // Act
                System.ComponentModel.DataAnnotations.ValidationResult result = _sut.GetValidationResult(TestValues.ValidIban, _validationContext);

                // Assert
                result.Should().Be(System.ComponentModel.DataAnnotations.ValidationResult.Success);
            }
 protected override ValidationResult IsValid(object value, ValidationContext validationContext)
 {
     if (value == null || String.IsNullOrEmpty(value.ToString())) return null;
     ValidationResult validationResult = null;
     if (!Regex.IsMatch(value.ToString(), Pattern))
         validationResult = new ValidationResult(ErrorMessage);
     return validationResult;
 }
        public void WeAreAbleToTransformValidationResultIntoException()
        {
            var error = new ValidationResult("error is fancy");
            var exception = error.ToException();

            Assert.IsNotNull(exception);
            Assert.AreEqual(error.ErrorMessage, exception.Message);
        }
        /// <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;
        }
 public static bool ValidateProduct(Products product, ValidationContext context, out ValidationResult result) {
     result = null;
     if (product.ReorderLevel < 0) {
         result = new ValidationResult("Reorder level is out of range", new[] { "ReorderLevel" });
         return false;
     }
     return true;
 }
Example #20
0
        /// <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;
        }
        public static IEnumerable<string> ExpandResults( ValidationResult result )
        {
            if( result == null )
            {
                return new List<string>();
            }

            return ExpandResults( new List<ValidationResult> { result } );
        }
 protected override ValidationResult IsValid(object value, ValidationContext validationContext)
 {
     if (value == null)
         return null;
     ValidationResult r = new ValidationResult("Invalid Postal Code!");
     if(!ValidateFunctions.validPostalCode(((String)value).ToUpper()))
         return r;
     return null;
 }
        public void AddResult(ValidationResult validationResult)
        {
            if (validationResult == null)
            {
                throw new ArgumentNullException("validationResult");
            }

            m_results.Add(validationResult);
        }
Example #24
0
        public static void MemberNames_can_be_set_through_two_args_constructor()
        {
            var validationResult = new ValidationResult("SomeErrorMessage", null);
            AssertEx.Empty(validationResult.MemberNames);

            var memberNames = new List<string>() { "firstMember", "secondMember" };
            validationResult = new ValidationResult("SomeErrorMessage", memberNames);
            Assert.True(memberNames.SequenceEqual(validationResult.MemberNames));
        }
 public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
 {
     var results = new List<ValidationResult>();
     if (Price <= 0)
     {
         var result = new ValidationResult("Price must be higher than zero.", new string[] { "Price" });
         results.Add(result);
     }
     return results;
 }
Example #26
0
            public void It_should_have_error_message_with_displayName()
            {
                _validationContext.DisplayName = "Property";

                // Act
                System.ComponentModel.DataAnnotations.ValidationResult result = _sut.GetValidationResult(TestValues.InvalidIban, _validationContext);

                // Assert
                result.ErrorMessage.Should().Be(string.Format(Resources.IbanAttribute_Invalid, _validationContext.DisplayName));
            }
        protected override ValidationResult IsValid( object value, ValidationContext validationContext )
        {
            var result = new ValidationResult (_errorMessage);
            decimal price;

            if(!decimal.TryParse(value.ToString(), out price) || price <= 0m)
                return result;

            return ValidationResult.Success;
        }
        protected override ValidationResult IsValid( object value, ValidationContext validationContext )
        {
            var result = new ValidationResult (_errorMessage);
            int count;

            if(!int.TryParse(value.ToString(), out count) || count < 0)
                return result;

            return ValidationResult.Success;
        }
        public void IsValid_NotEqualValue_ReturnsValidationResult()
        {
            AttributesModel model = new AttributesModel { Total = 10 };
            ValidationContext context = new ValidationContext(model);

            ValidationResult expected = new ValidationResult(attribute.FormatErrorMessage(context.DisplayName));
            ValidationResult actual = attribute.GetValidationResult(model.Sum, context);

            Assert.Equal(expected.ErrorMessage, actual.ErrorMessage);
        }
        public ComponentPropertyWrapViewModel(string propertyName, IPropertyValue propertyValue, string type, bool required)
        {
            mName = propertyName;

            mType = (CommonUtils.PropertyType)Enum.Parse(typeof(CommonUtils.PropertyType), type, true);
            mRequired = required;
            mPropertyValue = propertyValue;
            mErrorNumbericalValidationResult = new ValidationResult(string.Format("Field {0} is numerical", mName));
            mErrorRequiredValidationResult = new ValidationResult(string.Format("Field {0} is required", mName));
        }
        /// <summary>
        /// Initializes new instance of the <see cref="DateTimeCompareAttribute"/> 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 DateTimeCompareAttribute(string otherProperty, ValueComparison comparison)
            : base(otherProperty)
        {
            if (!Enum.IsDefined(typeof(ValueComparison), comparison))
                throw new ArgumentException("Undefined value.", "comparison");

            this.comparison = comparison;
            this.success = ValidationResult.Success;
            this.failure = new ValidationResult(String.Empty);
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var validationResult = new ValidationResult("Please enter a number with a maximum of 2 decimal places");
            
            if (value != null && value.ToString().IsValidMoneyDecimal())
            {
                validationResult = ValidationResult.Success;
            }

            return validationResult;
        }
 public ComponentTestingPropertyWrapViewModel(ControlSystemComponentTestingProperty componentTestingProperty, ControlSystemComponentTestingPropertyValue propertyValue)
 {
     mComponentTestingProperty = componentTestingProperty;
     mType = (CommonUtils.PropertyType)Enum.Parse(typeof(CommonUtils.PropertyType), componentTestingProperty.Type, true);
     var name = componentTestingProperty.Name;
     mRequired = componentTestingProperty.Required;
     mPropertyValue = propertyValue;
     mErrorNumbericalValidationResult = new ValidationResult(string.Format("Field {0} is numerical", name));
     mErrorRequiredValidationResult = new ValidationResult(string.Format("Field {0} is required", name));
     AcceptCommand = new DelegateCommand<object>(AcceptCommandHandler, CanModifyHandler);
 }
Example #34
0
 private static IEnumerable <ValidationError> GetInnerErrors(DA.ValidationResult validationResult)
 {
     if (validationResult is CompositeValidationResult)
     {
         CompositeValidationResult compositeValidationResult = (CompositeValidationResult)validationResult;
         return(compositeValidationResult.InnerResults
                .Select(x => new ValidationError(x.MemberNames, x.ErrorMessage, GetInnerErrors(x)))
                .ToList());
     }
     else
     {
         return(null);
     }
 }
        /// <inheritdoc/>
        public Task ValidateChangeSetItemAsync(
            SubmitContext context,
            ChangeSetItem item,
            Collection <ChangeSetItemValidationResult> validationResults,
            CancellationToken cancellationToken)
        {
            Ensure.NotNull(validationResults, "validationResults");
            DataModificationItem dataModificationItem = item as DataModificationItem;

            if (dataModificationItem != null)
            {
                object entity = dataModificationItem.Entity;

                // TODO GitHubIssue#50 : should this PropertyDescriptorCollection be cached?
                PropertyDescriptorCollection properties =
                    new DataAnnotations.AssociatedMetadataTypeTypeDescriptionProvider(entity.GetType())
                    .GetTypeDescriptor(entity).GetProperties();

                DataAnnotations.ValidationContext validationContext = new DataAnnotations.ValidationContext(entity);

                foreach (PropertyDescriptor property in properties)
                {
                    validationContext.MemberName = property.Name;

                    IEnumerable <DataAnnotations.ValidationAttribute> validationAttributes =
                        property.Attributes.OfType <DataAnnotations.ValidationAttribute>();
                    foreach (DataAnnotations.ValidationAttribute validationAttribute in validationAttributes)
                    {
                        object value = property.GetValue(entity);
                        DataAnnotations.ValidationResult validationResult =
                            validationAttribute.GetValidationResult(value, validationContext);
                        if (validationResult != DataAnnotations.ValidationResult.Success)
                        {
                            validationResults.Add(new ChangeSetItemValidationResult()
                            {
                                Id           = validationAttribute.GetType().FullName,
                                Message      = validationResult.ErrorMessage,
                                Severity     = EventLevel.Error,
                                Target       = entity,
                                PropertyName = property.Name
                            });
                        }
                    }
                }
            }

            return(Task.WhenAll());
        }
Example #36
0
            public void It_should_set_member_name()
            {
                // Act
                System.ComponentModel.DataAnnotations.ValidationResult result = _sut.GetValidationResult(TestValues.InvalidIban, _validationContext);

                // Assert
                if (string.IsNullOrEmpty(_validationContext.MemberName))
                {
                    result.MemberNames.Should().BeNullOrEmpty();
                }
                else
                {
                    result.MemberNames.Should()
                    .NotBeNull()
                    .And.BeEquivalentTo(_validationContext.MemberName);
                }
            }
Example #37
0
        protected virtual string Validate(object model, string propertyName)
        {
            string error = string.Empty;

            if (string.IsNullOrEmpty(propertyName))
            {
                return(error);
            }

            string curPropName = propertyName;
            object curmodel    = model;
            object value       = curmodel;


            string[] propTree = propertyName.Split('.');
            foreach (string prop in propTree)
            {
                var pi = value.GetType().GetProperty(prop);
                if (pi == null)
                {
                    break;
                }

                curPropName = prop;
                curmodel    = value;
                value       = pi.GetValue(value, null);
            }

            var results  = new List <DA.ValidationResult>(1);
            var validCtx = new DA.ValidationContext(curmodel, null, null)
            {
                MemberName = curPropName
            };
            bool result = DA.Validator.TryValidateProperty(value, validCtx, results);

            if (!result)
            {
                DA.ValidationResult validationResult = results.First();
                error = validationResult.ErrorMessage;
            }

            return(error);
        }
        protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            _validationResult = null;
            _validationResult = base.IsValid(value, validationContext);

            var ownerToTest = validationContext.ObjectInstance as Entity <int>;

            if (ownerToTest == null)
            {
                return(_validationResult);
            }

            var entityType = validationContext.ObjectType;

            DbSchemaName      = string.IsNullOrEmpty(DbSchemaName) ? entityType.EntityTableName() : DbSchemaName;
            DbColumnName      = string.IsNullOrEmpty(DbColumnName) ? validationContext.MemberName : DbColumnName;
            ValidationMessage = string.IsNullOrEmpty(ValidationMessage)
                                                ? string.Format("Property {0} must be unique across all \"{1}\" entities.", validationContext.MemberName, Inflector.Pluralize(entityType.Name))
                                                : ValidationMessage;

            var provider = ServiceLocator.Current.GetInstance <IDomainSessionFactoryProvider>();

            if (_validationResult == null)
            {
                int npiCount;
                using (var session = provider.SessionFactory.OpenStatelessSession())
                {
                    var query = String.Format("select Count({1}) from [dbo].[{0}] where [{1}]={2} {3}", DbSchemaName, DbColumnName, value, ownerToTest.IsPersisted ? "and Id <> " + ownerToTest.Id : "");
                    npiCount = session.CreateSQLQuery(query)
                               .UniqueResult <int>();
                }

                if (npiCount > 0)
                {
                    _validationResult = new System.ComponentModel.DataAnnotations.ValidationResult(ValidationMessage, new string[] { validationContext.MemberName });
                }
            }
            return(_validationResult);
        }
Example #39
0
        protected virtual void Validate(string propertyName, object value)
        {
            if (string.IsNullOrEmpty(propertyName))
            {
                throw new ArgumentNullException("propertyName");
            }

            string error = string.Empty;

            var results = new List <System.ComponentModel.DataAnnotations.ValidationResult>(2);

            bool result = Validator.TryValidateProperty(
                value,
                new ValidationContext(this, null, null)
            {
                MemberName = propertyName
            },
                results);

            if (!result && (value == null || ((value is int || value is long) && (int)value == 0) || (value is decimal && (decimal)value == 0)))
            {
                return;
            }

            if (!result)
            {
                System.ComponentModel.DataAnnotations.ValidationResult validationResult = results.First();
                if (!errorMessages.ContainsKey(propertyName))
                {
                    errorMessages.Add(propertyName, validationResult.ErrorMessage);
                }
            }

            else if (errorMessages.ContainsKey(propertyName))
            {
                errorMessages.Remove(propertyName);
            }
        }
        protected override DA.ValidationResult IsValid(object value, DA.ValidationContext validationContext)
        {
            if (value == null)
            {
                return(DA.ValidationResult.Success);
            }

            var results = new List <DA.ValidationResult>();

            if (value is IEnumerable)
            {
                // value is an enumerable, so we have to validate each element
                // individually.

                var enumerable = value as IEnumerable;
                int index      = 0;
                foreach (var val in enumerable)
                {
                    if (val != null)
                    {
                        // Validate the list element and wrap any validation info
                        // inside a composite result

                        var tmpResults = new List <DA.ValidationResult>();
                        var tmpContext = new DA.ValidationContext(val);
                        DA.Validator.TryValidateObject(val, tmpContext, tmpResults, true);

                        if (tmpResults.Count > 0)
                        {
                            var result = new CompositeValidationResult("Failed to validate property.", $"{validationContext.DisplayName}#{index}", tmpResults);
                            results.Add(result);
                        }
                    }
                    else
                    {
                        // Cannot validate a null element in a list

                        var result = new DA.ValidationResult("Element is null.", new string[] { $"{validationContext.DisplayName}#{index}" });
                        results.Add(result);
                    }

                    index++;
                }
            }
            else
            {
                // Validate value normally and keep trace of the sub-results

                var context = new DA.ValidationContext(value);
                DA.Validator.TryValidateObject(value, context, results, true);
            }

            // Wrap all sub results inside a composite result to be able to gather
            // useful information
            if (results.Count > 0)
            {
                return(new CompositeValidationResult($"Failed to validate property.", validationContext.DisplayName, results));
            }
            else
            {
                return(DA.ValidationResult.Success);
            }
        }
Example #41
0
 protected ValidationResult(ValidationResult validationResult)
 {
 }
Example #42
0
 public ValidationException(ValidationResult validationResult, ValidationAttribute validatingAttribute, object value)
     : this(validationResult != null ? validationResult.ErrorMessage : null, validatingAttribute, value)
 {
     this.ValidationResult = validationResult;
 }