public async Task ValidateAsync_WithHandlers_HandlersGetCalledOnceForEachRule() { // Arrange var rules = new IValidationRule <int>[] { new GreaterThanRule(5), new GreaterThanRule(7), new LowerThanRule(10), new LowerThanRule(12) }; var handlers = new[] { new TestHandler <int>(), new TestHandler <int>(), new TestHandler <int>() }; var items = new[] { 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }; var validator = new Validator <int>(rules, handlers); // Act await validator.ValidateAsync(items); // Assert Assert.All(handlers, h => Assert.Equal(4, h.HandleCount)); }
/// <summary> /// Register a rule /// </summary> /// <param name="validationRule"></param> public void AddValidationRule(IValidationRule <T> validationRule) { if (validationRule != null && validationRule.ValidationExpression != null) { ValidationRulesForExecutution.Add(validationRule); } }
public async Task ValidateAsync_WithMixedResults_MergeResults() { // Arrange var rules = new IValidationRule <int>[] { new GreaterThanRule(5), new GreaterThanRule(7), new LowerThanRule(10), new LowerThanRule(12) }; var handlers = Array.Empty <IValidationRuleHandler <int> >(); var items = new[] { 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }; var validator = new Validator <int>(rules, handlers); // Act var results = await validator.ValidateAsync(items); // Assert Assert.Equal(10, results.Count()); Assert.Equal(new[] { "NOT_GREATER_THAN_5", "NOT_GREATER_THAN_7" }, results[4].ErrorCodes()); Assert.Equal(new[] { "NOT_GREATER_THAN_5", "NOT_GREATER_THAN_7" }, results[5].ErrorCodes()); Assert.Equal(new[] { "NOT_GREATER_THAN_7" }, results[6].ErrorCodes()); Assert.Equal(new[] { "NOT_GREATER_THAN_7" }, results[7].ErrorCodes()); Assert.True(results[8].Valid()); Assert.True(results[9].Valid()); Assert.Equal(new[] { "NOT_LOWER_THAN_10" }, results[10].ErrorCodes()); Assert.Equal(new[] { "NOT_LOWER_THAN_10" }, results[11].ErrorCodes()); Assert.Equal(new[] { "NOT_LOWER_THAN_10", "NOT_LOWER_THAN_12" }, results[12].ErrorCodes()); Assert.Equal(new[] { "NOT_LOWER_THAN_10", "NOT_LOWER_THAN_12" }, results[13].ErrorCodes()); }
private void HandleValidationRule( ChangeOfChargesMessage changeOfChargesMessage, IValidationRule validationRule, HubRequestValidationResult validationResult) { const string unknownServerError = "Unknown server error"; try { if (_ruleConfigurations == null) { validationResult.Add(new ValidationError("VR900", unknownServerError)); _logger.LogError($"{nameof(_ruleConfigurations)} was null"); return; } var ruleValidationResult = validationRule.Validate(changeOfChargesMessage, _ruleConfigurations); if (ruleValidationResult.ValidatedSuccessfully is false) { validationResult.Add(ruleValidationResult.ValidationError); } } catch (RuleNotFoundException ruleNotFoundException) { validationResult.Add(new ValidationError("VRXYZ", unknownServerError)); _logger.LogError(ruleNotFoundException, "Rule configuration could not be found"); } catch (RuleCouldNotBeMappedException ruleCouldNotBeMappedException) { validationResult.Add(new ValidationError("VRXYZ", unknownServerError)); _logger.LogError(ruleCouldNotBeMappedException, "Rule value could not be mapped"); } }
/// <summary> /// 添加额外的验证规则 /// </summary> /// <param name="rule"></param> public void AddValidationRule(IValidationRule rule) { if (rule != null) { _rules.Add(rule); } }
/// <summary> /// Determines whether or not a rule should execute. /// </summary> /// <param name="rule">The rule</param> /// <param name="propertyPath">Property path (eg Customer.Address.Line1)</param> /// <param name="context">Contextual information</param> /// <returns>Whether or not the validator can execute.</returns> public bool CanExecute(IValidationRule rule, string propertyPath, ValidationContext context) { if (rule.RuleSets.Length == 0 && _rulesetsToExecute.Count == 0) { return(true); } if (rule.RuleSets.Length == 0 && _rulesetsToExecute.Count > 0 && _rulesetsToExecute.Contains("default", StringComparer.OrdinalIgnoreCase)) { return(true); } if (rule.RuleSets.Length > 0 && _rulesetsToExecute.Count > 0 && _rulesetsToExecute.Intersect(rule.RuleSets).Any()) { return(true); } if (_rulesetsToExecute.Contains("*")) { return(true); } return(false); }
public EntityValidator(IValidationRule <TEntity> rule) { if (rule != null) { AddRule("Default", rule); } }
/// <summary> /// Determines whether or not a rule should execute. /// </summary> /// <param name="rule">The rule</param> /// <param name="propertyPath">Property path (eg Customer.Address.Line1)</param> /// <param name="context">Contextual information</param> /// <returns>Whether or not the validator can execute.</returns> public bool CanExecute(IValidationRule rule, string propertyPath, ValidationContext context) { // By default we ignore any rules part of a RuleSet. if (!string.IsNullOrEmpty(rule.RuleSet)) return false; return true; }
public void SetUp() { _mocks = new MockRepository(); _mockedValidator = _mocks.StrictMock <IValidator <int> >(); _mockedFormatter = _mocks.StrictMock <IValidationErrorMessageFormatter <int> >(); _composedObjectRule = new ComposedObjectMustBeValidRule <string, int>(s => s.Length, _mockedValidator, _mockedFormatter); }
public bool CanExecute( IValidationRule rule, string propertyPath, ValidationContext context) { return string.IsNullOrEmpty(rule.RuleSet); }
/// <summary> /// Determines whether or not a rule should execute. /// </summary> /// <param name="rule">The rule</param> /// <param name="propertyPath">Property path (eg Customer.Address.Line1)</param> /// <param name="context">Contextual information</param> /// <returns>Whether or not the validator can execute.</returns> public bool CanExecute(IValidationRule rule, string propertyPath, ValidationContext context) { if (string.IsNullOrEmpty(rule.RuleSet)) return true; if (!string.IsNullOrEmpty(rule.RuleSet) && rulesetsToExecute.Length > 0 && rulesetsToExecute.Contains(rule.RuleSet)) return true; if (rulesetsToExecute.Contains("*")) return true; return false; }
/// <summary> /// Determines whether or not a rule should execute. /// </summary> /// <param name="rule">The rule</param> /// <param name="propertyPath">Property path (eg Customer.Address.Line1)</param> /// <param name="context">Contextual information</param> /// <returns>Whether or not the validator can execute.</returns> public bool CanExecute(IValidationRule rule, string propertyPath, ValidationContext context) { // Validator selector only applies to the top level. // If we're running in a child context then this means that the child validator has already been selected // Because of this, we assume that the rule should continue (ie if the parent rule is valid, all children are valid) return(context.IsChildContext || memberNames.Any(x => x == propertyPath || propertyPath.StartsWith(x + "."))); }
public void SetUp() { _mocks = new MockRepository(); _mockedValidator = _mocks.StrictMock <IValidator <string> >(); _mockedFormatter = _mocks.StrictMock <IValidationErrorMessageFormatter <string> >(); _inheritedObjectRule = new InheritedObjectMustBeValidRule <string, string>(_mockedValidator, _mockedFormatter); }
public bool IsPropertyValid(string propertyName, object value) { RemoveErrors(propertyName); switch (propertyName) { case "NameProject": validationRule = new ValidateNameProjectRule(); if (!validationRule.IsValid(value)) { AddError(propertyName, validationRule.ErrorMessage); return(false); } break; case "Customer": validationRule = new ValidateCustomerRule(); if (!validationRule.IsValid(value)) { AddError(propertyName, validationRule.ErrorMessage); return(false); } break; } return(true); }
/// <summary> /// Gets validators for <see cref="IValidationRule"/>. /// </summary> /// <param name="validationRule">Validator.</param> /// <returns>enumeration.</returns> public static IEnumerable <IPropertyValidator> GetValidators(this IValidationRule validationRule) { return(validationRule .Components .NotNull() .Where(component => component.HasNoCondition()) .Select(component => component.Validator)); }
internal ValidationPredicate(IValidationRule <TType> rule, Predicate <TType> predicate) { rule.ThrowIfNull(); predicate.ThrowIfNull(); m_rule = rule; m_predicate = predicate; }
public void SetUp() { _mocks = new MockRepository(); _mockedValidationRule = _mocks.StrictMock <IValidationRule <string> >(); _mockedFormatter = _mocks.StrictMock <IValidationErrorMessageFormatter <string> >(); _collectionRule = new CollectionMustBeValidRule <FakeObjectToValidate, string>(i => i.ListOfStrings, _mockedValidationRule, _mockedFormatter); }
public void Rules() { IValidationRule rule = this.mockery.NewMock <IValidationRule>(); this.testee.Add(rule); Assert.AreEqual(1, this.testee.Count); }
public GraphqlController(ISchema schema, IValidationRule validationRule, IHttpContextAccessor httpContextAccessor) { _schema = schema; _validationRule = validationRule; _httpContextAccessor = httpContextAccessor; }
public void Property_should_return_null_when_it_is_not_a_property_being_validated() { builder = _validator.RuleFor(x => "Foo"); IValidationRule <Person, string> rule = null; builder.Configure(r => rule = r); rule.Member.ShouldBeNull(); }
/// <inheritdoc cref="Owasp.Esapi.Interfaces.IValidator.AddRule(string, IValidationRule)" /> public void AddRule(string name, IValidationRule rule) { // NOTE: "name" will be validated by the dictionary if (rule == null) { throw new ArgumentNullException("rule"); } rules.Add(name, rule); }
/// <summary> /// Initializes a new instance of the <see cref="And{T}"/> class. /// </summary> /// <param name="rule1">First rule.</param> /// <param name="rule2">Second rule.</param> /// <param name="breakOnFirstError">Value indicating whether rule should break on first error.</param> public And(IValidationRule <T> rule1, IValidationRule <T> rule2, bool breakOnFirstError = false) { FirstRule = rule1.AssertArgumentNotNull(nameof(rule1)); LastRule = rule2.AssertArgumentNotNull(nameof(rule2)); Property = rule1.Property; BreakOnFirstError = breakOnFirstError; }
void with_method_build( IValidationRule <ModelA> rule) { rule .For(m => m.Name) .Assert(_is.NotNull) .Assert(_is.NotEmpty); }
/// <summary> /// Determines whether or not a rule should execute. /// </summary> /// <param name="rule">The rule</param> /// <param name="propertyPath">Property path (eg Customer.Address.Line1)</param> /// <param name="context">Contextual information</param> /// <returns>Whether or not the validator can execute.</returns> public bool CanExecute(IValidationRule rule, string propertyPath, ValidationContext context) { if (string.IsNullOrEmpty(rule.RuleSet) && rulesetsToExecute.Length == 0) return true; if (string.IsNullOrEmpty(rule.RuleSet) && rulesetsToExecute.Length > 0 && rulesetsToExecute.Contains("default", StringComparer.OrdinalIgnoreCase)) return true; if (!string.IsNullOrEmpty(rule.RuleSet) && rulesetsToExecute.Length > 0 && rulesetsToExecute.Contains(rule.RuleSet)) return true; if (rulesetsToExecute.Contains("*")) return true; return false; }
/// <summary> /// 添加验证规则 /// </summary> /// <param name="rule">验证规则</param> public void AddValidationRule(IValidationRule rule) { if (rule == null) { return; } _rules.Add(rule); }
public void PropertyDescription_should_return_property_name_split() { var builder = _validator.RuleFor(x => x.DateOfBirth); IValidationRule <Person, DateTime> rule = null; builder.Configure(r => rule = r); rule.GetDisplayName(null).ShouldEqual("Date Of Birth"); }
public ValidatableObject(IValidationRule <T> rule) : this() { Validations = new List <IValidationRule <T> > { rule }; Validate(); }
public static IValidationRule <T> WithMessage <T>(this IValidationRule <T> rule, string message) { if (message?.Length > 0) { rule.ValidationMessage = message; } return(rule); }
public void AggregateValidationRule(IValidationRule ValidationRule) { if (ValidationRuleList == null) { ValidationRuleList = new List <IValidationRule>(); } ValidationRuleList.Add(ValidationRule); }
/// <summary> /// Adds a child rule to the composite rule. /// </summary> /// <param name="rule">The child rule to add.</param> public override void Add( IValidationRule rule) { if (children == null) { children = new List<IValidationRule>(); } children.Add(rule); }
public void UseValidator(IValidator <TMember> validator) { if (validator == null) { throw new ArgumentNullException(nameof(validator)); } this.rule = new CustomValidatorRule <TMember>(validator); }
public void PropertyDescription_should_return_custom_property_name() { var builder = _validator.RuleFor(x => x.DateOfBirth); IValidationRule <Person, DateTime> rule = null; builder.Configure(r => rule = r); builder.NotEqual(default(DateTime)).WithName("Foo"); rule.GetDisplayName(null).ShouldEqual("Foo"); }
public async Task ValidateRule <TValidationRule, TViewModel>(IValidationRule <TViewModel> validationRule, TViewModel viewModel) where TValidationRule : class, IValidationRule <TViewModel> where TViewModel : class { if (validationRule != null) { await validationRule.Validate(viewModel); } }
public void AddRule(IValidationRule rule) { foreach (var r in _rules) { if (r.GetType() == rule.GetType()) return; } _rules.Add(rule); }
internal void AddPrecondition(IValidationRule <TTarget> precondition) { if (preconditions == null) { preconditions = new List <IValidationRule <TTarget> >(); } preconditions.Add(precondition); }
public void Rule_for_a_non_memberexpression_should_not_generate_property_name() { var builder = _validator.RuleFor(x => x.CalculateSalary()); IValidationRule <Person, int> rule = null; builder.Configure(r => rule = r); rule.GetDisplayName(null).ShouldBeNull(); rule.PropertyName.ShouldBeNull(); }
/// <summary> /// Adds a rule to the current validator. /// </summary> /// <param name="rule"></param> public void AddRule(IValidationRule rule) { if (currentRuleSetName != null) { rule.RuleSet = currentRuleSetName; } nestedValidators.Add(rule); }
public bool CanExecute( IValidationRule rule, string propertyPath, ValidationContext context) { if (!string.IsNullOrEmpty(rule.RuleSet) && rule.RuleSet.Equals(RuleSetName)) return true; return false; }
/// <summary> /// Staticka metoda na vytvorenie default vysledku so stavom OK /// </summary> /// <param name="fromRule"></param> /// <returns></returns> public static ValidationItemResult CreateDefaultOk(IValidationRule fromRule) { var ret = new ValidationItemResult(fromRule); ret.ValidationResultState = ResultState.Ok; ret.ResultTooltip = string.Empty; ret.ResultMessage = string.Empty; ret.Details = new DetailedResultInfo() { LineNumber = null }; return ret; }
public void SetUp() { theModel = new SimpleModel(); r1 = MockRepository.GenerateStub<IValidationRule>(); r2 = MockRepository.GenerateStub<IValidationRule>(); theSource = typeof(ConfiguredValidationSource); theContext = ValidationContext.For(theModel); theStep = new ValidationStep(theModel.GetType(), theSource, new[] { r1, r2 }); }
internal Rule(IValidationRule rule) { _validationRule = rule; if (rule is HandlerRule) { this.Key = (rule as HandlerRule).GetKeyString(); } else { this.Key = rule.GetType().FullName; } }
protected bool HasChildValidator(IValidationRule rule) { foreach (var validator in rule.Validators) { if (validator is ChildValidatorAdaptor) { return true; } if (validator is IDelegatingValidator) { if (((IDelegatingValidator) validator).InnerValidator is ChildValidatorAdaptor) { return true; } } } return false; }
public void SetUp() { mappingSet = new MappingSetImpl(); engine = new ValidationRulesEngine(mappingSet); rule1 = MockRepository.GenerateMock<IValidationRule>(); rule2 = MockRepository.GenerateMock<IValidationRule>(); result1 = new ValidationResult(rule1); result2 = new ValidationResult(rule2); rule1.Stub(r => r.Run(mappingSet)).Return(result1); rule2.Stub(r => r.Run(mappingSet)).Return(result2); engine.AddRule(rule1); engine.AddRule(rule2); }
public void SetUp() { theModel = new ContactModel(); theType = theModel.GetType(); r1 = MockRepository.GenerateStub<IValidationRule>(); r2 = MockRepository.GenerateStub<IValidationRule>(); r3 = MockRepository.GenerateStub<IValidationRule>(); theMatchingSource = ConfiguredValidationSource.For(type => type == theType, r1, r2); theOtherSource = ConfiguredValidationSource.For(type => type == typeof(int), r3); theGraph = ValidationGraph.BasicGraph(); theGraph.RegisterSource(theMatchingSource); theGraph.RegisterSource(theOtherSource); theContext = ValidationContext.For(theModel); thePlan = ValidationPlan.For(theType, theGraph); }
protected bool IsModelLevelRule(IValidationRule rule) { var propRule = rule as PropertyRule; return propRule != null && propRule.Expression.GetMember() == null && propRule.Expression.IsParameterExpression(); }
/// <summary> /// 添加验证规则 /// </summary> /// <param name="rule">验证规则</param> public void AddValidationRule( IValidationRule rule ) { if ( rule == null ) return; _rules.Add( rule ); }
public ObserverResult NextRule(IValidationRule rule) { Log("\tNext rule: " + rule.ToString() + ".. "); return ObserverResult.Continue; }
public void AddRule(IValidationRule rule) { this._rules.Add(rule); }
public void AddRule(string name, IValidationRule rule) { Impl.AddRule(name, rule); }
/// <summary> /// Initializes a new instance of the <see cref="MappingValidator"/> class. /// </summary> /// <param name="mappingManager">The mapping manager that is used to map types to and from their Solr representation.</param> /// <param name="rules">Validation rules</param> public MappingValidator(IReadOnlyMappingManager mappingManager, IValidationRule[] rules) { this.mappingManager = mappingManager; this.rules = rules; }
protected bool IsIncludeRule(IValidationRule rule) { return rule is IncludeRule; }
/// <summary> /// Adds a rule to the set. /// </summary> public void Add(IValidationRule rule) { _rules.Add(rule); }
/// <summary> /// Creates and sets new Validation Rule(inherited from <see cref="IValidationRule"/>). /// </summary> public void AssignValidationRule() { RangeValidationRule rule = new RangeValidationRule(NumericQuestion.Types.IntegerType, null, null); rule.RegexRule = new RegexValidationRule(""); ValidationRule = rule; }
public ValidationRuleLoadException(IValidationRule rule) : this(null, rule) { }
/// <summary> /// Konstruktor vysledku validacie jedneho pravidla /// </summary> /// <param name="fromRule"></param> public ValidationItemResult(IValidationRule fromRule) { this.FromRule = fromRule; // dafult je vsetko ok this.ValidationResultState = ResultState.Ok; }
public ValidationRuleLoadException(string msg, IValidationRule rule) : base("The '" + rule.Name + "' validation rule failed to load. " + msg) { ValidationRule = rule; }
/// <summary> /// Removes a rule from the set. /// </summary> public void Remove(IValidationRule rule) { _rules.Remove(rule); }
/// <summary> /// Method to assign validation control to ValidationRule field. /// </summary> public void AssignValidationRule() { ValidationRule = new RangeValidationRule(Type, MinValue, MaxValue); }
/// <summary> /// Builds the child rules for the given rule from the given XML node. /// </summary> /// <param name="parent">The rule to build the children for.</param> /// <param name="parentNode">The XML node containing the definition(s) /// of the chlid rules.</param> private void GetChildren( IValidationRule parent, XmlNode parentNode) { foreach (XmlNode ruleNode in parentNode) { string nodeName = ruleNode.Name; // null?? // if the rule has properties, set them on the rule object if (nodeName == "properties") { foreach (XmlNode paramNode in ruleNode.ChildNodes) { string attrName = StringUtilities.Capitalize(paramNode.Name); if (ReflectionUtilities.HasProperty(parent, attrName)) { ReflectionUtilities.SetPropertyValue(parent, attrName, paramNode.InnerText); } } // } else if (nodeName == "validator") { } else { IValidationRule rule = ValidationRuleFactory.Make(StringUtilities.Capitalize(nodeName)); if (rule != null) { if ((ruleNode.Attributes != null) && (ruleNode.Attributes.Count > 0)) { NameValueCollection attributes = new NameValueCollection(); foreach (XmlAttribute attr in ruleNode.Attributes) { attributes.Add(attr.Name, attr.Value); } ReflectionUtilities.Deserialize(rule, attributes); } //if (rule != null) { // // if there are any attributes on the rule node, try setting // // the corresponding property of the rule object // foreach (XmlAttribute attr in ruleNode.Attributes) { // string attrName = StringUtilities.Capitalize(attr.Name); // // this is really hokey, but it works for now // if ((attrName == "ErrorId") && ReflectionUtilities.HasProperty(rule, "ErrorId")) { // try { // // ReflectionUtilities.SetPropertyValue(rule, "ErrorId", long.Parse(attr.Value)); // ((BaseRule)rule).ErrorId = long.Parse(attr.Value); // } catch { // // TODO: log the failure? // } // } else if (ReflectionUtilities.HasProperty(rule, attrName)) { // ReflectionUtilities.SetPropertyValue(rule, attrName, attr.Value); // } // } // get the children of the rule GetChildren(rule, ruleNode); // add the rule to the parent's list of children parent.Add(rule); } // TODO: else log it? } } }
public void DefineRule(string key, IValidationRule rule) { _rules[key] = rule; }