/// <summary> /// Gets the registered validators. /// </summary> /// <param name="parentType">Type of the parent.</param> /// <param name="property">The property.</param> /// <param name="runWhenPhase">The run when phase.</param> /// <returns></returns> public IValidator[] GetValidators(Type parentType, PropertyInfo property, RunWhen runWhenPhase) { if (parentType == null) { throw new ArgumentNullException("parentType"); } if (property == null) { throw new ArgumentNullException("property"); } IValidator[] validators = registry.GetValidators(this, parentType, property, runWhenPhase); if (inferValidators && validators.Length == 0) { Type defaultValidatorForType = (Type)type2Validator[property.PropertyType]; if (defaultValidatorForType != null) { validators = new IValidator[] { (IValidator)Activator.CreateInstance(defaultValidatorForType) }; validators[0].Initialize(registry, property); } } SortValidators(validators); return(validators); }
/// <summary> /// Validates the parameter. /// </summary> /// <param name="invocation">The invocation.</param> /// <param name="parameterPosition">The parameter position.</param> /// <param name="runWhen">The run when.</param> /// <param name="errors">The errors.</param> protected virtual void ValidateParameter(IInvocation invocation, int parameterPosition, RunWhen runWhen, ErrorSummary errors) { MethodInfo method = invocation.Method; ParameterInfoMeta parameterInfoMeta; IValidator[] validators = methodValidatorMetaStore.GetValidatorsFor(method, parameterPosition, null, runWhen, out parameterInfoMeta); foreach (IValidator validator in validators) { IPropertyAccessAware propertyAccessAware = (IPropertyAccessAware)validator; object value = invocation.Arguments[parameterPosition]; if (parameterInfoMeta == ParameterInfoMeta.ParamsArray) { ValidateParamsArray(validator, propertyAccessAware, value, errors); continue; } propertyAccessAware.PropertyAccessor = delegate { return invocation.Arguments[parameterPosition]; }; if (validator.IsValid(value)) continue; AppendError(validator, errors); } }
/// <summary> /// Determines whether the specified instance is valid. /// <para> /// All validators are run for the specified <see cref="RunWhen"/> phase. /// </para> /// </summary> /// <param name="objectInstance">The object instance to be validated (cannot be null).</param> /// <param name="runWhen">Restrict the set returned to the phase specified</param> /// <returns> /// <see langword="true"/> if the specified instance is valid; otherwise, <see langword="false"/>. /// </returns> public bool IsValid(object objectInstance, RunWhen runWhen) { if (objectInstance == null) { throw new ArgumentNullException("objectInstance"); } bool isValid; ErrorSummary summary = new ErrorSummary(); IValidator[] validators = GetValidators(objectInstance, runWhen); SortValidators(validators); isValid = validationPerformer.PerformValidation( objectInstance, validators, contributors, runWhen, summary); SetErrorSummaryForInstance(objectInstance, summary); return(isValid); }
public virtual bool Validate(RunWhen runWhen) { this.ThrowIfRunnerNotSet(); this.RunValidation(runWhen); return(this.ValidationSummary.HasErrors == false); }
public ErrorSummary IsValid(object instance, RunWhen runWhen) { ErrorSummary errors = new ErrorSummary(); errors.RegisterErrorMessage("someKey", "error"); return(errors); }
/// <summary> /// Determines whether the specified instance is valid. Returns an /// <see cref="ErrorSummary"/> that will be appended to the existing /// error summary for an object. /// </summary> /// <param name="instance">The instance.</param> /// <param name="runWhen">The run when.</param> /// <returns></returns> public ErrorSummary IsValid(object instance, RunWhen runWhen) { if (instance == null) throw new ArgumentNullException("instance"); Type contributorType = this.GetType(); Type instanceType = instance.GetType(); if(!initializedTypesByContributorType.Contains(contributorType)) { // Double checked lock so we don't get two threads adding the same type at the same time lock (initializedTypesByContributorType.SyncRoot) { if (!initializedTypesByContributorType.Contains(contributorType)) { initializedTypesByContributorType[contributorType] = ArrayList.Synchronized(new ArrayList()); } } } ArrayList initialized = initializedTypesByContributorType[contributorType] as ArrayList; if (!initialized.Contains(instanceType)) { lock (initialized.SyncRoot) { if (!initialized.Contains(instanceType)) { Initialize(instanceType); initialized.Add(instanceType); } } } return IsValidInternal(instance, runWhen); }
/// <summary> /// /// </summary> /// <param name="declaringType"></param> /// <param name="runWhen"></param> /// <returns></returns> protected IValidator[] GetValidatorsForDeclaringType(Type declaringType, RunWhen runWhen) { IValidator[] validators = registry.GetValidators(this, declaringType, runWhen); SortValidators(validators); return(validators); }
private bool IsValidatorOnPhase(IValidator validator, RunWhen when) { if (validator.RunWhen == RunWhen.Everytime) { return(true); } return((validator.RunWhen & when) != 0); }
private IValidator[] GetValidators(object objectInstance, RunWhen runWhen) { if (objectInstance == null) { throw new ArgumentNullException("objectInstance"); } IValidator[] validators = GetValidatorsForDeclaringType(objectInstance.GetType(), runWhen); return(validators); }
private void RunValidation(RunWhen runWhen) { this.ValidationSummary = new ValidationSummary(); if (Validable.ValidationRunner.IsValid(this, runWhen) == false) { this.ValidationSummary = Validable.ValidationRunner.GetSummary(this); } this.CustomValidation(); }
bool IValidationPerformer.PerformValidation(object objectInstance, IEnumerable<IValidator> validators, IEnumerable<IValidationContributor> contributors, RunWhen runWhen, ErrorSummary summaryToPopulate) { foreach (IValidator validator in validators) { if (!validator.IsValid(objectInstance)) { string name = validator.FriendlyName ?? validator.Name; summaryToPopulate.RegisterErrorMessage(name, validator.ErrorMessage); } } if(contributors != null) (this as IValidationPerformer).ExecuteContributors(objectInstance, contributors, summaryToPopulate, runWhen); bool isValid = !summaryToPopulate.HasError; return isValid; }
/// <summary> /// Determines whether the specified instance is valid. /// </summary> /// <param name="instance">The instance.</param> /// <param name="runWhen">The run when.</param> /// <returns></returns> public ErrorSummary IsValid(object instance, RunWhen runWhen) { ErrorSummary errors = new ErrorSummary(); IInvocation invocation = instance as IInvocation; if (invocation == null) return errors; for (int i = 0; i < invocation.Arguments.Length; i++) { ValidateParameter(invocation, i, runWhen, errors); } return errors; }
/// <summary> /// Gets all validators associated with a property. /// <para> /// The validators returned are initialized. /// </para> /// </summary> /// <param name="validatorRunner">The validator runner.</param> /// <param name="targetType">Target type.</param> /// <param name="property">The property.</param> /// <param name="runWhen">Restrict the set returned to the phase specified</param> /// <returns>A Validator array</returns> public IValidator[] GetValidators( IValidatorRunner validatorRunner, Type targetType, PropertyInfo property, RunWhen runWhen) { var builders = (object[])attrsPerProperty[property]; if (builders == null) { var metaDataTypeProperty = _metaDataType.GetProperty(property.Name); if (metaDataTypeProperty == null) { return((IValidator[])(new ArrayList()).ToArray(typeof(IValidator))); } builders = metaDataTypeProperty.GetCustomAttributes(typeof(IValidatorBuilder), true); // Attribute order cannot be guaranted in C# // this way we assure there order by Type Name Array.Sort(builders, new TypeNameComparer()); attrsPerProperty[property] = builders; foreach (IValidatorBuilder builder in builders) { builder.Initialize(this, property); } } var validators = new List <IValidator>(); foreach (IValidatorBuilder builder in builders) { IValidator validator = builder.Build(validatorRunner, targetType); if (!IsValidatorOnPhase(validator, runWhen)) { continue; } validator.Initialize(this, property); validators.Add(validator); } return(validators.ToArray()); }
/// <summary> /// Gets all validators associated with a <see cref="Type"/>. /// <para> /// The validators returned are initialized. /// </para> /// </summary> /// <param name="validatorRunner">The validator runner.</param> /// <param name="targetType">Target type.</param> /// <param name="runWhen">Restrict the set returned to the phase specified</param> /// <returns>A Validator array</returns> public IValidator[] GetValidators(IValidatorRunner validatorRunner, Type targetType, RunWhen runWhen) { PropertyInfo[] properties = (PropertyInfo[]) propertiesPerType[targetType]; if (properties == null) { propertiesPerType[targetType] = properties = ResolveProperties(targetType); } ArrayList list = new ArrayList(); foreach(PropertyInfo prop in properties) { list.AddRange(GetValidators(validatorRunner, targetType, prop, runWhen)); } return (IValidator[]) list.ToArray(typeof(IValidator)); }
/// <summary> /// Determines whether the specified instance is valid. /// </summary> /// <param name="instance">The instance.</param> /// <param name="runWhen">The run when.</param> /// <returns></returns> public ErrorSummary IsValid(object instance, RunWhen runWhen) { ErrorSummary errors = new ErrorSummary(); IInvocation invocation = instance as IInvocation; if (invocation == null) { return(errors); } for (int i = 0; i < invocation.Arguments.Length; i++) { ValidateParameter(invocation, i, runWhen, errors); } return(errors); }
/// <summary> /// Determines whether the specified instance is valid. Returns an /// <see cref="ErrorSummary"/> that will be appended to the existing /// error summary for an object. /// </summary> /// <param name="instance">The instance.</param> /// <param name="when">The when.</param> /// <returns></returns> protected override ErrorSummary IsValidInternal(object instance, RunWhen when) { ErrorSummary summary = new ErrorSummary(); // perform validation on each validator container interfaces foreach (Type validatorContainerType in GetValidatorContainerInterfacesForType(instance.GetType())) { // don't run any other contributors IValidationContributor[] contributors = null; validationPerformer.PerformValidation( instance, RequestValidatorsToRegistry(validatorContainerType, when), contributors, when, summary ); } return(summary); }
/// <summary> /// Gets all validators associated with a <see cref="Type"/>. /// <para> /// The validators returned are initialized. /// </para> /// </summary> /// <param name="validatorRunner">The validator runner.</param> /// <param name="targetType">Target type.</param> /// <param name="runWhen">Restrict the set returned to the phase specified</param> /// <returns>A Validator array</returns> public IValidator[] GetValidators(IValidatorRunner validatorRunner, Type targetType, RunWhen runWhen) { _metaDataType = ((MetadataTypeAttribute)targetType.GetCustomAttributes(typeof(MetadataTypeAttribute), false)[0]).MetadataClassType; var properties = (PropertyInfo[]) propertiesPerType[targetType]; if (properties == null) { propertiesPerType[targetType] = properties = ResolveProperties(targetType); } var list = new List<IValidator>(); foreach (PropertyInfo prop in properties) { list.AddRange(GetValidators(validatorRunner, targetType, prop, runWhen)); } return list.ToArray(); }
/// <summary> /// Performs the fields validation for the specified action. /// </summary> /// <param name="runWhen">Use validators appropriate to the action being performed.</param> /// <returns>True if no validation error was found</returns> public virtual bool IsValid(RunWhen runWhen) { failedProperties = new Dictionary <PropertyInfo, ArrayList>(); // first check if the object itself is valid bool returnValue = Runner.IsValid(ARObjectInstance, runWhen); // then check the components that are properties if the object foreach (PropertyInfo propinfo in GetNestedPropertiesToValidate(ARObjectInstance)) { object propval = propinfo.GetValue(ARObjectInstance, null); if (propval != null) { bool propValid = Runner.IsValid(propval, runWhen); if (!propValid) { ErrorSummary propSummary = Runner.GetErrorSummary(propval); string[] propErrors = propSummary.GetErrorsForProperty(propinfo.Name); failedProperties.Add(propinfo, new ArrayList(propErrors)); } returnValue &= propValid; } } if (!returnValue) { Type type = ARObjectInstance.GetType(); ErrorSummary summary = Runner.GetErrorSummary(ARObjectInstance); foreach (string property in summary.InvalidProperties) { string[] errors = summary.GetErrorsForProperty(property); failedProperties.Add(type.GetProperty(property), new ArrayList(errors)); } } return(returnValue); }
/// <summary> /// Performs the fields validation for the specified action. /// </summary> /// <param name="runWhen">Use validators appropriate to the action being performed.</param> /// <returns>True if no validation error was found</returns> public virtual bool IsValid(RunWhen runWhen) { failedProperties = new Dictionary<PropertyInfo, ArrayList>(); // first check if the object itself is valid bool returnValue = Runner.IsValid(ARObjectInstance, runWhen); // then check the components that are properties if the object foreach (PropertyInfo propinfo in GetNestedPropertiesToValidate(ARObjectInstance)) { object propval = propinfo.GetValue(ARObjectInstance, null); if (propval != null) { bool propValid = Runner.IsValid(propval, runWhen); if (!propValid) { ErrorSummary propSummary = Runner.GetErrorSummary(propval); string[] propErrors = propSummary.GetErrorsForProperty(propinfo.Name); failedProperties.Add(propinfo, new ArrayList(propErrors)); } returnValue &= propValid; } } if (!returnValue) { Type type = ARObjectInstance.GetType(); ErrorSummary summary = Runner.GetErrorSummary(ARObjectInstance); foreach (string property in summary.InvalidProperties) { string[] errors = summary.GetErrorsForProperty(property); failedProperties.Add(type.GetProperty(property), new ArrayList(errors)); } } return returnValue; }
/// <summary> /// Determines whether the specified instance is valid. Returns an /// <see cref="ErrorSummary"/> that will be appended to the existing /// error summary for an object. /// </summary> /// <param name="instance">The instance.</param> /// <param name="runWhen">The run when.</param> /// <returns></returns> public ErrorSummary IsValid(object instance, RunWhen runWhen) { if (instance == null) { throw new ArgumentNullException("instance"); } Type contributorType = this.GetType(); Type instanceType = instance.GetType(); if (!initializedTypesByContributorType.Contains(contributorType)) { // Double checked lock so we don't get two threads adding the same type at the same time lock (initializedTypesByContributorType.SyncRoot) { if (!initializedTypesByContributorType.Contains(contributorType)) { initializedTypesByContributorType[contributorType] = ArrayList.Synchronized(new ArrayList()); } } } ArrayList initialized = initializedTypesByContributorType[contributorType] as ArrayList; if (!initialized.Contains(instanceType)) { lock (initialized.SyncRoot) { if (!initialized.Contains(instanceType)) { Initialize(instanceType); initialized.Add(instanceType); } } } return(IsValidInternal(instance, runWhen)); }
/// <summary> /// Determines whether the specified instance is valid. Returns an /// <see cref="ErrorSummary"/> that will be appended to the existing /// error summary for an object. /// </summary> /// <param name="instance">The instance.</param> /// <param name="runWhen">The run when.</param> /// <returns></returns> protected override ErrorSummary IsValidInternal(object instance, RunWhen runWhen) { ErrorSummary errorSummary = new ErrorSummary(); ArrayList methods = (ArrayList)methodsPerType[instance.GetType()]; if (methods == null) { return(errorSummary); } foreach (SelfValidationMeta meta in methods) { if (!IsMetaOnPhase(meta, runWhen)) { continue; } MethodInfo methodInfo = meta.MethodInfo; methodInfo.Invoke(instance, new object[] { errorSummary }); } return(errorSummary); }
public SelfValidationMeta(MethodInfo methodInfo, RunWhen runWhen, int executionOrder) { this.methodInfo = methodInfo; this.runWhen = runWhen; this.executionOrder = executionOrder; }
/// <summary> /// Builds all of the validators for a given method, parameter position, with the defined RunWhen. /// </summary> /// <param name="method">The method.</param> /// <param name="parameterPosition">The parameter position.</param> /// <param name="runner">The runner.</param> /// <param name="runWhen">The run when.</param> /// <param name="parameterInfoMeta">Metadata about the parameters such as whether or not it is params</param> /// <returns></returns> public IValidator[] GetValidatorsFor(MethodInfo method, int parameterPosition, ValidatorRunner runner, RunWhen runWhen, out ParameterInfoMeta parameterInfoMeta) { MethodValidatorMetaInfo meta = type2MetaInfo[method.DeclaringType]; List<IValidator> validators = new List<IValidator>(); IValidatorBuilder[] builders = meta.GetBuilders(method, parameterPosition, out parameterInfoMeta); ParameterInfo[] parameters = method.GetParameters(); foreach (IValidatorBuilder builder in builders) { IValidator validator = builder.Build(runner, typeof(MethodInfo)); if (!IsValidatorOnPhase(validator, runWhen)) continue; if (string.IsNullOrEmpty(validator.FriendlyName)) validator.FriendlyName = parameters[parameterPosition].Name; validator.Initialize(registry, null); validators.Add(validator); } return validators.ToArray(); }
public IValidator[] GetValidators(ValidatorRunner validatorRunner, Type targetType, PropertyInfo property, RunWhen runWhen) { throw new NotSupportedException(); }
private static bool IsMetaOnPhase(SelfValidationMeta meta, RunWhen when) { return (when == RunWhen.Everytime || meta.RunWhen == RunWhen.Everytime || ((meta.RunWhen & when) != 0)); }
/// <summary> /// Determines whether the specified instance is valid. Returns an /// <see cref="ErrorSummary"/> that will be appended to the existing /// error summary for an object. /// </summary> /// <param name="instance">The instance.</param> /// <param name="runWhen">The run when.</param> /// <returns></returns> protected override ErrorSummary IsValidInternal(object instance, RunWhen runWhen) { ErrorSummary errorSummary = new ErrorSummary(); ArrayList methods = (ArrayList)methodsPerType[instance.GetType()]; if (methods == null) return errorSummary; foreach (SelfValidationMeta meta in methods) { if (!IsMetaOnPhase(meta, runWhen)) continue; MethodInfo methodInfo = meta.MethodInfo; methodInfo.Invoke(instance, new object[] {errorSummary}); } return errorSummary; }
private IValidator[] RequestValidatorsToRegistry(Type validatorContainerType, RunWhen when) { return validatorRegistry.GetValidators( validatorRunner, validatorContainerType, when); }
/// <summary> /// Gets all validators associated with a property. /// <para> /// The validators returned are initialized. /// </para> /// </summary> /// <param name="validatorRunner">The validator runner.</param> /// <param name="targetType">Target type.</param> /// <param name="property">The property.</param> /// <param name="runWhen">Restrict the set returned to the phase specified</param> /// <returns>A Validator array</returns> public IValidator[] GetValidators(IValidatorRunner validatorRunner, Type targetType, PropertyInfo property, RunWhen runWhen) { object[] builders = (object[])this.attrsPerProperty[property]; if (builders == null) { builders = property.GetCustomAttributes(typeof(IValidatorBuilder), true); this.attrsPerProperty[property] = builders; } ArrayList validators = new ArrayList(); foreach (IValidatorBuilder builder in builders) { IValidator validator = builder.Build(validatorRunner, targetType); if (!IsValidatorOnPhase(validator, runWhen)) { continue; } validator.Initialize(this, property); // Translate the error message of the validator. This way we can use the error message of a validator as resource key. string translatedErrorMessage = TranslateErrorMessage(validator.ErrorMessage); if (translatedErrorMessage != null) { validator.ErrorMessage = translatedErrorMessage; } validators.Add(validator); } return((IValidator[])validators.ToArray(typeof(IValidator))); }
/// <summary> /// Gets all validators associated with a <see cref="Type"/>. /// <para> /// The validators returned are initialized. /// </para> /// </summary> /// <param name="validatorRunner">The validator runner.</param> /// <param name="targetType">Target type.</param> /// <param name="runWhen">Restrict the set returned to the phase specified</param> /// <returns>A Validator array</returns> public IValidator[] GetValidators(IValidatorRunner validatorRunner, Type targetType, RunWhen runWhen) { _metaDataType = ((MetadataTypeAttribute)targetType.GetCustomAttributes(typeof(MetadataTypeAttribute), false)[0]).MetadataClassType; var properties = (PropertyInfo[])propertiesPerType[targetType]; if (properties == null) { propertiesPerType[targetType] = properties = ResolveProperties(targetType); } var list = new List <IValidator>(); foreach (PropertyInfo prop in properties) { list.AddRange(GetValidators(validatorRunner, targetType, prop, runWhen)); } return(list.ToArray()); }
private IValidator[] GetValidators(object objectInstance, RunWhen runWhen) { if (objectInstance == null) throw new ArgumentNullException("objectInstance"); IValidator[] validators = GetValidatorsForDeclaringType(objectInstance.GetType(), runWhen); return validators; }
/// <summary> /// /// </summary> /// <param name="declaringType"></param> /// <param name="runWhen"></param> /// <returns></returns> protected IValidator[] GetValidatorsForDeclaringType(Type declaringType, RunWhen runWhen) { IValidator[] validators = registry.GetValidators(this, declaringType, runWhen); SortValidators(validators); return validators; }
/// <summary> /// Gets the registered validators. /// </summary> /// <param name="parentType">Type of the parent.</param> /// <param name="property">The property.</param> /// <param name="runWhenPhase">The run when phase.</param> /// <returns></returns> public IValidator[] GetValidators(Type parentType, PropertyInfo property, RunWhen runWhenPhase) { if (parentType == null) throw new ArgumentNullException("parentType"); if (property == null) throw new ArgumentNullException("property"); IValidator[] validators = registry.GetValidators(this, parentType, property, runWhenPhase); if (inferValidators && validators.Length == 0) { Type defaultValidatorForType = (Type) type2Validator[property.PropertyType]; if (defaultValidatorForType != null) { validators = new IValidator[] {(IValidator) Activator.CreateInstance(defaultValidatorForType)}; validators[0].Initialize(registry, property); } } SortValidators(validators); return validators; }
/// <summary> /// Determines whether the specified instance is valid. /// <para> /// All validators are run for the specified <see cref="RunWhen"/> phase. /// </para> /// </summary> /// <param name="objectInstance">The object instance to be validated (cannot be null).</param> /// <param name="runWhen">Restrict the set returned to the phase specified</param> /// <returns> /// <see langword="true"/> if the specified instance is valid; otherwise, <see langword="false"/>. /// </returns> public bool IsValid(object objectInstance, RunWhen runWhen) { if (objectInstance == null) throw new ArgumentNullException("objectInstance"); bool isValid; ErrorSummary summary = new ErrorSummary(); IValidator[] validators = GetValidators(objectInstance, runWhen); SortValidators(validators); isValid = validationPerformer.PerformValidation( objectInstance, validators, contributors, runWhen, summary); SetErrorSummaryForInstance(objectInstance, summary); return isValid; }
void IValidationPerformer.ExecuteContributors(object objectInstance, IEnumerable <IValidationContributor> contributors, ErrorSummary summaryToPopulate, RunWhen runWhen) { foreach (IValidationContributor contributor in contributors) { ErrorSummary errors = contributor.IsValid(objectInstance, runWhen); summaryToPopulate.RegisterErrorsFrom(errors); } }
bool IValidationPerformer.PerformValidation(object objectInstance, IEnumerable <IValidator> validators, IEnumerable <IValidationContributor> contributors, RunWhen runWhen, ErrorSummary summaryToPopulate) { foreach (IValidator validator in validators) { if (!validator.IsValid(objectInstance)) { string name = validator.FriendlyName ?? validator.Name; summaryToPopulate.RegisterErrorMessage(name, validator.ErrorMessage); } } if (contributors != null) { (this as IValidationPerformer).ExecuteContributors(objectInstance, contributors, summaryToPopulate, runWhen); } bool isValid = !summaryToPopulate.HasError; return(isValid); }
/// <summary> /// Determines whether the specified instance is valid. Returns an /// <see cref="ErrorSummary"/> that will be appended to the existing /// error summary for an object. /// </summary> /// <param name="instance">The instance.</param> /// <param name="when">The when.</param> /// <returns></returns> protected abstract ErrorSummary IsValidInternal(object instance, RunWhen when);
/// <summary> /// Performs the fields validation for the specified action. /// </summary> /// <param name="runWhen">Use validators appropriate to the action being performed.</param> /// <returns>True if no validation error was found</returns> /// <remarks>Forwards the call to <see cref="ActualValidator"/>.</remarks> public virtual bool IsValid(RunWhen runWhen) { return ActualValidator.IsValid(runWhen); }
/// <summary> /// Gets all validators associated with a property. /// <para> /// The validators returned are initialized. /// </para> /// </summary> /// <param name="validatorRunner">The validator runner.</param> /// <param name="targetType">Target type.</param> /// <param name="property">The property.</param> /// <param name="runWhen">Restrict the set returned to the phase specified</param> /// <returns>A Validator array</returns> public IValidator[] GetValidators( ValidatorRunner validatorRunner, Type targetType, PropertyInfo property, RunWhen runWhen) { object[] builders = (object[]) attrsPerProperty[property]; if (builders == null) { builders = property.GetCustomAttributes(typeof (IValidatorBuilder), true); attrsPerProperty[property] = builders; } ArrayList validators = new ArrayList(); foreach (IValidatorBuilder builder in builders) { IValidator validator = builder.Build(validatorRunner, targetType); if (!IsValidatorOnPhase(validator, runWhen)) continue; validator.Initialize(this, property); validators.Add(validator); } return (IValidator[]) validators.ToArray(typeof (IValidator)); }
/// <summary> /// Builds all of the validators for a given method, parameter position, with the defined RunWhen. /// </summary> /// <param name="method">The method.</param> /// <param name="parameterPosition">The parameter position.</param> /// <param name="runner">The runner.</param> /// <param name="runWhen">The run when.</param> /// <param name="parameterInfoMeta">Metadata about the parameters such as whether or not it is params</param> /// <returns></returns> public IValidator[] GetValidatorsFor(MethodInfo method, int parameterPosition, ValidatorRunner runner, RunWhen runWhen, out ParameterInfoMeta parameterInfoMeta) { MethodValidatorMetaInfo meta = type2MetaInfo[method.DeclaringType]; List <IValidator> validators = new List <IValidator>(); IValidatorBuilder[] builders = meta.GetBuilders(method, parameterPosition, out parameterInfoMeta); ParameterInfo[] parameters = method.GetParameters(); foreach (IValidatorBuilder builder in builders) { IValidator validator = builder.Build(runner, typeof(MethodInfo)); if (!IsValidatorOnPhase(validator, runWhen)) { continue; } if (string.IsNullOrEmpty(validator.FriendlyName)) { validator.FriendlyName = parameters[parameterPosition].Name; } validator.Initialize(registry, null); validators.Add(validator); } return(validators.ToArray()); }
/// <summary> /// Gets all validators associated with a property. /// <para> /// The validators returned are initialized. /// </para> /// </summary> /// <param name="validatorRunner">The validator runner.</param> /// <param name="targetType">Target type.</param> /// <param name="property">The property.</param> /// <param name="runWhen">Restrict the set returned to the phase specified</param> /// <returns>A Validator array</returns> public IValidator[] GetValidators( IValidatorRunner validatorRunner, Type targetType, PropertyInfo property, RunWhen runWhen) { object[] builders = (object[]) attrsPerProperty[property]; if (builders == null) { builders = property.GetCustomAttributes(typeof(IValidatorBuilder), true); // Attribute order cannot be guaranted in C# // this way we assure there order by Type Name Array.Sort(builders, new TypeNameComparer()); attrsPerProperty[property] = builders; foreach(IValidatorBuilder builder in builders) { builder.Initialize(this, property); } } ArrayList validators = new ArrayList(); foreach(IValidatorBuilder builder in builders) { IValidator validator = builder.Build(validatorRunner, targetType); if (!IsValidatorOnPhase(validator, runWhen)) continue; validator.Initialize(this, property); validators.Add(validator); } return (IValidator[]) validators.ToArray(typeof(IValidator)); }
/// <summary> /// Determines whether the specified instance is valid. Returns an /// <see cref="ErrorSummary"/> that will be appended to the existing /// error summary for an object. /// </summary> /// <param name="instance">The instance.</param> /// <param name="when">The when.</param> /// <returns></returns> protected override ErrorSummary IsValidInternal(object instance, RunWhen when) { ErrorSummary summary = new ErrorSummary(); // perform validation on each validator container interfaces foreach (Type validatorContainerType in GetValidatorContainerInterfacesForType(instance.GetType())) { // don't run any other contributors IValidationContributor[] contributors = null; validationPerformer.PerformValidation( instance, RequestValidatorsToRegistry(validatorContainerType, when), contributors, when, summary ); } return summary; }
private static bool IsValidatorOnPhase(IValidator validator, RunWhen when) { if (validator.RunWhen == RunWhen.Everytime) return true; return ((validator.RunWhen & when) != 0); }
/// <summary> /// Gets all validators associated with a <see cref="Type"/>. /// <para> /// The validators returned are initialized. /// </para> /// </summary> /// <param name="validatorRunner">The validator runner.</param> /// <param name="targetType">Target type.</param> /// <param name="runWhen">Restrict the set returned to the phase specified</param> /// <returns>A Validator array</returns> public IValidator[] GetValidators(IValidatorRunner validatorRunner, Type targetType, RunWhen runWhen) { PropertyInfo[] properties = (PropertyInfo[])propertiesPerType[targetType]; if (properties == null) { this.propertiesPerType[targetType] = properties = ResolveProperties(targetType); } ArrayList list = new ArrayList(); foreach (PropertyInfo prop in properties) { list.AddRange(GetValidators(validatorRunner, targetType, prop, runWhen)); } return((IValidator[])list.ToArray(typeof(IValidator))); }
private static bool IsMetaOnPhase(SelfValidationMeta meta, RunWhen when) { return(when == RunWhen.Everytime || meta.RunWhen == RunWhen.Everytime || ((meta.RunWhen & when) != 0)); }
/// <summary> /// Gets all validators associated with a <see cref="Type"/>. /// <para> /// The validators returned are initialized. /// </para> /// </summary> /// <param name="validatorRunner">The validator runner.</param> /// <param name="targetType">Target type.</param> /// <param name="runWhen">Restrict the set returned to the phase specified</param> /// <returns>A Validator array</returns> public IValidator[] GetValidators(IValidatorRunner validatorRunner, Type targetType, RunWhen runWhen) { PropertyInfo[] properties = (PropertyInfo[])propertiesPerType[targetType]; if (properties == null) { propertiesPerType[targetType] = properties = ResolveProperties(targetType); } var list = new List <IValidator>(); foreach (PropertyInfo prop in properties) { list.AddRange(GetValidators(validatorRunner, targetType, prop, runWhen)); } return(list.ToArray()); }
/// <summary> /// Gets all validators associated with a property. /// <para> /// The validators returned are initialized. /// </para> /// </summary> /// <param name="validatorRunner">The validator runner.</param> /// <param name="targetType">Target type.</param> /// <param name="property">The property.</param> /// <param name="runWhen">Restrict the set returned to the phase specified</param> /// <returns>A Validator array</returns> public IValidator[] GetValidators(IValidatorRunner validatorRunner, Type targetType, PropertyInfo property, RunWhen runWhen) { object[] builders = (object[])this.attrsPerProperty[property]; if (builders == null) { builders = property.GetCustomAttributes(typeof(IValidatorBuilder), true); this.attrsPerProperty[property] = builders; } ArrayList validators = new ArrayList(); foreach (IValidatorBuilder builder in builders) { IValidator validator = builder.Build(validatorRunner, targetType); if (!IsValidatorOnPhase(validator, runWhen)) continue; validator.Initialize(this, property); // Translate the error message of the validator. This way we can use the error message of a validator as resource key. string translatedErrorMessage = TranslateErrorMessage(validator.ErrorMessage); if (translatedErrorMessage != null) { validator.ErrorMessage = translatedErrorMessage; } validators.Add(validator); } return (IValidator[])validators.ToArray(typeof(IValidator)); }
void IValidationPerformer.ExecuteContributors(object objectInstance, IEnumerable<IValidationContributor> contributors, ErrorSummary summaryToPopulate, RunWhen runWhen) { foreach (IValidationContributor contributor in contributors) { ErrorSummary errors = contributor.IsValid(objectInstance, runWhen); summaryToPopulate.RegisterErrorsFrom(errors); } }
/// <summary> /// Performs the fields validation for the specified action. /// </summary> /// <param name="runWhen">Use validators appropriate to the action being performed.</param> /// <returns>True if no validation error was found</returns> /// <remarks>Forwards the call to <see cref="ActualValidator"/>.</remarks> public virtual bool IsValid(RunWhen runWhen) { return(ActualValidator.IsValid(runWhen)); }
/// <summary> /// Validates the parameter. /// </summary> /// <param name="invocation">The invocation.</param> /// <param name="parameterPosition">The parameter position.</param> /// <param name="runWhen">The run when.</param> /// <param name="errors">The errors.</param> protected virtual void ValidateParameter(IInvocation invocation, int parameterPosition, RunWhen runWhen, ErrorSummary errors) { MethodInfo method = invocation.Method; ParameterInfoMeta parameterInfoMeta; IValidator[] validators = methodValidatorMetaStore.GetValidatorsFor(method, parameterPosition, null, runWhen, out parameterInfoMeta); foreach (IValidator validator in validators) { IPropertyAccessAware propertyAccessAware = (IPropertyAccessAware)validator; object value = invocation.Arguments[parameterPosition]; if (parameterInfoMeta == ParameterInfoMeta.ParamsArray) { ValidateParamsArray(validator, propertyAccessAware, value, errors); continue; } propertyAccessAware.PropertyAccessor = delegate { return(invocation.Arguments[parameterPosition]); }; if (validator.IsValid(value)) { continue; } AppendError(validator, errors); } }
public bool IsValid(Validable validable, RunWhen runWhen) { return(this.runner.IsValid(validable, runWhen)); }
public ErrorSummary IsValid(object instance, RunWhen runWhen) { ErrorSummary errors = new ErrorSummary(); errors.RegisterErrorMessage("someKey", "error"); return errors; }
private IValidator[] GetValidators(object objectInstance, RunWhen runWhen) { if (objectInstance == null) throw new ArgumentNullException("objectInstance"); IValidator[] validators = registry.GetValidators(this, objectInstance.GetType(), runWhen); SortValidators(validators); return validators; }
/// <summary> /// Determines whether the specified instance is valid. /// <para> /// All validators are run for the specified <see cref="RunWhen"/> phase. /// </para> /// </summary> /// <param name="objectInstance">The object instance to be validated (cannot be null).</param> /// <param name="runWhen">Restrict the set returned to the phase specified</param> /// <returns> /// <see langword="true"/> if the specified instance is valid; otherwise, <see langword="false"/>. /// </returns> public bool IsValid(object objectInstance, RunWhen runWhen) { if (objectInstance == null) throw new ArgumentNullException("objectInstance"); bool isValid; ErrorSummary summary = new ErrorSummary(); IEnumerable<IValidator> validators = GetValidators(objectInstance, runWhen); isValid = PerformValidation(objectInstance, validators, summary); return isValid; }
private IValidator[] RequestValidatorsToRegistry(Type validatorContainerType, RunWhen when) { return(validatorRegistry.GetValidators( validatorRunner, validatorContainerType, when)); }