/// <summary> /// Validates the current MainModel /// </summary> /// <param name="model"></param> /// <param name="throwException">Determine if it should fire a MVPValidationException on validation error</param> /// <returns>True if sucessfully validated</returns> protected virtual bool DoValidate(T model, bool throwException) { #if FRAMEWORK_3 IValidatorRunner runner = new ValidatorRunner(new CachedValidationRegistry()); if (runner.IsValid(model)) { return(true); } ErrorSummary errors = runner.GetErrorSummary(model); for (int i = 0; i < errors.ErrorsCount; i++) { ErrorList.Add(new ValidationError(errors.InvalidProperties[i], errors.ErrorMessages[i])); } if (throwException) { // TODO: Colocar a string em um resource throw new MVPValidationException( string.Format("Validation has failed with {0} errors. See inner exceptions for details.", errors.ErrorsCount), ErrorList); } #endif return(false); }
public void Setup() { validator = new ValidatorRunner(new CachedValidationRegistry()); accessor = new StaticValidatorAccessor(); accessor.Validator = validator; ValidEventListner.ValidatorAccessor = accessor; }
/// <summary> /// Generates a client-side validation script based on the attributes of the modelToValidate. /// </summary> /// <param name="modelToValidate">The model to validate.</param> /// <param name="formId">The client ID of the form.</param> /// <param name="propertyNameToElementId">Delegate that can translate properties of the model to form elements.</param> /// <returns></returns> public string GenerateClientScript(object modelToValidate, string formId, Func <string, string> propertyNameToElementId) { // Create a BrowserValidationConfiguration instance to store all validation rules. BrowserValidationConfiguration config = this._browserValidatorProvider.CreateConfiguration(null); // Create a ValidatorRunner that is needed to obtain the validators for the given modelToValidate. var validatorRunner = new ValidatorRunner(this._validatorRegistry); // Create a script generator and that is linked to the BrowserValidationConfiguration IBrowserValidationGenerator generator = _browserValidatorProvider.CreateGenerator(config, InputElementType.Undefined, propertyNameToElementId); // Get all validators for the given modelToValidate IValidator[] validators = _validatorRegistry.GetValidators(validatorRunner, modelToValidate.GetType(), RunWhen.Everytime); // Iterate the validators and call ApplyBrowserValidation to generate the validation rules and messages into the BrowserValidationConfiguration. foreach (var validator in validators) { validator.ApplyBrowserValidation(config, InputElementType.Undefined, generator, null, propertyNameToElementId(validator.Property.Name)); } // Generate the validation script block var sb = new StringBuilder(); sb.Append("<script type=\"text/javascript\">" + Environment.NewLine); // Call CreateBeforeFormClosed of the BrowserValidationConfiguration. This generates the client script. // Note: it's called CreateBeforeFormClosed because originally (in Monorail), it was used to only // generate some extra scripts for validation. sb.Append(config.CreateBeforeFormClosed(formId)); sb.Append("</script>" + Environment.NewLine); return(sb.ToString()); }
private static void ValidateContext(WebServerConfiguration context) { var validator = new ValidatorRunner(true, new CachedValidationRegistry()); if (!validator.IsValid(context)) { string[] errorList = validator.GetErrorSummary(context).ErrorMessages; var messageBuilder = new StringBuilder("The CassisniContext contained invalid data. "); foreach (string item in errorList) { messageBuilder.AppendLine(item); } throw new ValidationException(messageBuilder.ToString()); } if (context.PortNumber == 0) { string message = "You must specify a port number. Auto-configured port numbers are not supported untill I figure out how to return the selected port number."; throw new NotImplementedException(message); } if (!File.Exists(Path.Combine(context.WebSiteRootFolder, context.DefaultWebPageFileName))) { string message = string.Format("Could not find the default page '{0}'", Path.Combine(context.WebSiteRootFolder, context.DefaultWebPageFileName)); throw new FileNotFoundException(message); } }
/// <summary> /// Creates the validator runner. /// </summary> /// <returns></returns> protected virtual IValidatorRunner CreateRunner() { IValidationContributor[] contributors = new IValidationContributor[] { contributor }; IValidatorRunner runner = new ValidatorRunner(contributors, new CachedValidationRegistry()); return(runner); }
static void Main(string[] args) { var order = new Order { Product = new Product { Name = "Widget", MinQuantity = 5, MaxQuantity = 100 }, Quantity = 50 }; var runner = new ValidatorRunner(new CachedValidationRegistry()); if (runner.IsValid(order)) { Console.WriteLine("The order is valid!"); } else { ErrorSummary summary = runner.GetErrorSummary(order); foreach (var invalidProperty in summary.InvalidProperties) { Console.WriteLine("{0} is invalid because:", invalidProperty); foreach (var error in summary.GetErrorsForProperty(invalidProperty)) { Console.WriteLine("\t * {0}", error); } } } Console.ReadLine(); }
public void Should_Validate_Object_Using_Validators_From_Metadata() { var runner = new ValidatorRunner(new CachedMetadataValidationRegistry()); var person = new Person(); Assert.IsFalse(runner.IsValid(person)); person = new Person{Name = "stan"}; Assert.IsTrue(runner.IsValid(person)); }
/// <errorSummary> /// Determines whether the specified instance is valid. /// </errorSummary> /// <param name="instance">The instance.</param> /// <param name="fieldValue">The field value.</param> /// <returns> /// <c>true</c> if the specified instance is valid; otherwise, <c>false</c>. /// </returns> public override bool IsValid(object instance, object fieldValue) { ValidatorRunner runner = new ValidatorRunner(validationRegistry.BaseRegistry); bool valid = runner.IsValid(instance); if (!valid) { errorSummary = runner.GetErrorSummary(instance); } return(valid); }
public void Should_Validate_Object_Using_Validators_From_Metadata() { var runner = new ValidatorRunner(new CachedMetadataValidationRegistry()); var person = new Person(); Assert.IsFalse(runner.IsValid(person)); person = new Person { Name = "stan" }; Assert.IsTrue(runner.IsValid(person)); }
public ErrorSummary Validate() { ValidatorRunner vr = new ValidatorRunner(true, new CachedValidationRegistry()); if (!vr.IsValid(this)) { return(vr.GetErrorSummary(this)); } else { return(null); } }
public IEnumerable <ErrorInfo> GetErrors <ENTITY>(ENTITY entity) where ENTITY : DomainEntity { var result = new List <ErrorInfo>(); var runner = new ValidatorRunner(registry); if (entity != null && !runner.IsValid(entity)) { var errorSummary = runner.GetErrorSummary(entity); var errorInfos = errorSummary.InvalidProperties.SelectMany( prop => errorSummary.GetErrorsForProperty(prop), (prop, err) => new ErrorInfo(prop, err)); result.AddRange(errorInfos); } return(result); }
public CrudReport Validate <ENTITY>(ENTITY entity) where ENTITY : DomainEntity { var crudReport = new CrudReport(); var runner = new ValidatorRunner(registry); if (runner.IsValid(entity)) { crudReport.Success = true; } else { crudReport.AddErrorInfos(GetErrors(entity)); } return(crudReport); }
public void ExecutesCustomContributors() { ValidatorRunner runnerWithContributor = new ValidatorRunner(true, new CachedValidationRegistry(), new IValidationContributor[] { new AlwaysErrorContributor() }); object target = new object(); Assert.IsFalse(runnerWithContributor.IsValid(target)); ErrorSummary errors = runnerWithContributor.GetErrorSummary(target); Assert.IsTrue(errors.HasError); Assert.AreEqual(1, errors.ErrorsCount); string[] errorsForKey = errors.GetErrorsForProperty("someKey"); Assert.AreEqual(1, errorsForKey.Length); Assert.AreEqual("error", errorsForKey[0]); }
public void ValidationOrderTest() { ValidatorRunner runner = new ValidatorRunner(new CachedValidationRegistry()); Supplier supplier = new Supplier(); supplier.Password = "******"; runner.IsValid(supplier); ErrorSummary summary = runner.GetErrorSummary(supplier); Assert.IsNotNull(summary); Assert.AreEqual("This is a required field", summary.ErrorMessages[0]); Assert.AreEqual("Fields do not match", summary.ErrorMessages[1]); Assert.AreEqual("This is a required field", summary.ErrorMessages[2]); }
public void Init() { runner = new ValidatorRunner(new CachedValidationRegistry()); }
public void SetUp() { cachedValidationRegistry = new CachedValidationRegistry(new ResourceManager("Castle.Components.Validator.Messages", typeof(CachedValidationRegistry).Assembly)); runner = new ValidatorRunner(cachedValidationRegistry); }
public void ExecutesCustomContributors() { ValidatorRunner runnerWithContributor = new ValidatorRunner(true, new CachedValidationRegistry(), new IValidationContributor[] {new AlwaysErrorContributor()}); object target = new object(); Assert.IsFalse(runnerWithContributor.IsValid(target)); ErrorSummary errors = runnerWithContributor.GetErrorSummary(target); Assert.IsTrue(errors.HasError); Assert.AreEqual(1, errors.ErrorsCount); string[] errorsForKey = errors.GetErrorsForProperty("someKey"); Assert.AreEqual(1, errorsForKey.Length); Assert.AreEqual("error", errorsForKey[0]); }
public IValidator[] GetValidators(ValidatorRunner validatorRunner, Type targetType, PropertyInfo property, RunWhen runWhen) { throw new NotSupportedException(); }
public virtual void Init() { runner = new ValidatorRunner(new CachedValidationRegistry()); }
/// <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> /// Initializes a new instance of the <see cref="AbstractFormRelatedHelper"/> class. /// </summary> /// <param name="validatorRegistry">The validator registry.</param> /// <param name="validatorRunner">The validator runner.</param> protected AbstractFormRelatedHelper(IValidatorRegistry validatorRegistry, ValidatorRunner validatorRunner) { this.validatorRegistry = validatorRegistry; this.validatorRunner = validatorRunner; }
internal static void AddNestedPropertyValidationErrorMessages(List <string> errorMessages, object instance, ValidatorRunner runner) { foreach (PropertyInfo propinfo in GetNestedPropertiesToValidate(instance)) { object propval = propinfo.GetValue(instance, null); if (propval != null) { ErrorSummary summary = runner.GetErrorSummary(propval); if (summary != null) { errorMessages.AddRange(summary.ErrorMessages); } } } }