public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var result = base.BindModel(controllerContext, bindingContext);
            if (result == null)
            {
                return result;
            }

            var runner = new ValidatorRunner(new CachedValidationRegistry());
            if (runner.IsValid(result))
            {
                return result;
            }

            var summary = runner.GetErrorSummary(result);
            var modelState = bindingContext.ModelState;
            foreach (var invalidProperty in summary.InvalidProperties)
            {
                foreach (var error in summary.GetErrorsForProperty(invalidProperty))
                {
                    modelState.AddModelError(invalidProperty, error);
                }
            }

            return result;
        }
 public CastleValidatorRulesProvider()
 {
     registry = new CachedValidationRegistry();
     runner = new ValidatorRunner(registry);
     ruleEmitters.AddSingle<NonEmptyValidator>(x => new RequiredRule());
     ruleEmitters.AddSingle<CreditCardValidator>(x => new DataTypeRule(DataTypeRule.DataType.CreditCardLuhn));
     ruleEmitters.AddMultiple<DateTimeValidator>(x => new Rule[] {
         new RequiredRule(),
         new DataTypeRule(DataTypeRule.DataType.DateTime)
     });
     ruleEmitters.AddMultiple<DateValidator>(x => new Rule[] {
         new RequiredRule(),
         new DataTypeRule(DataTypeRule.DataType.Date)
     });
     ruleEmitters.AddMultiple<IntegerValidator>(x => new Rule[] {
         new RequiredRule(),
         new DataTypeRule(DataTypeRule.DataType.Integer)
     });
     ruleEmitters.AddMultiple<IValidator>(x => {
         if ((x is DecimalValidator) || (x is DoubleValidator) || (x is SingleValidator)) {
             return new Rule[] {
                 new RequiredRule(),
                 new DataTypeRule(DataTypeRule.DataType.Decimal)
             };
         } else
             return null;
     });
     ruleEmitters.AddSingle<LengthValidator>(ConstructStringLengthRule);
     ruleEmitters.AddSingle<RangeValidator>(ConstructRangeRule);
     ruleEmitters.AddSingle<EmailValidator>(x => new DataTypeRule(DataTypeRule.DataType.EmailAddress));
     ruleEmitters.AddSingle<RegularExpressionValidator>(x => new RegularExpressionRule(x.Expression, x.RegexRule.Options));
     ruleEmitters.AddSingle<SameAsValidator>(x => new ComparisonRule(x.PropertyToCompare, ComparisonRule.Operator.Equals));
     ruleEmitters.AddSingle<NotSameAsValidator>(x => new ComparisonRule(x.PropertyToCompare, ComparisonRule.Operator.DoesNotEqual));
 }
Exemple #3
0
        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();
        }
		/// <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;
		}
		/// <summary>
		/// Constructs and configures an <see cref="IValidator"/>
		/// instance based on the properties set on the attribute instance.
		/// </summary>
		/// <param name="validatorRunner"></param>
		/// <param name="type"></param>
		/// <returns></returns>
		public override IValidator Build(ValidatorRunner validatorRunner, Type type)
		{
			GroupNotEmptyValidator validator = (GroupNotEmptyValidator)
			                                   validatorRunner.ExtendedProperties[group];
			if (validator == null)
			{
				validatorRunner.ExtendedProperties[group] = validator
				                                            = new GroupNotEmptyValidator(group);
			}
			ConfigureValidatorMessage(validator);

			return validator;
		}
 public void Index([DataBind("ContactRequest")] ContactRequest request)
 {
     var runner = new ValidatorRunner(new CachedValidationRegistry());
     if (!runner.IsValid(request))
     {
         ErrorSummary summary = runner.GetErrorSummary(request);
         PropertyBag["ContactRequest"] = request;
         PropertyBag["error"] = summary;
     }
     else
     {
         var parameter = new Dictionary<string, object> { { "request", request } };
         var message = RenderMailMessage("contact", null, (IDictionary)parameter);
         message.Encoding = System.Text.Encoding.UTF8;
         DeliverEmail(message);
         RedirectToAction("Thanks");
     }
 }
		/// <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(ValidatorRunner 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>
		/// Constructs and configures an <see cref="IValidator"/>
		/// instance based on the properties set on the attribute instance.
		/// </summary>
		public virtual IValidator Build(ValidatorRunner validatorRunner, Type type)
		{
			return Build();
		}
		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);
					}
				}
			}
		}
Exemple #10
0
		/// <summary>
		/// Invoked by the framework in order to give a chance to
		/// obtain other services
		/// </summary>
		/// <param name="provider">The service proviver</param>
		public virtual void Service(IServiceProvider provider)
		{
			var loggerFactory = (ILoggerFactory)provider.GetService(typeof(ILoggerFactory));

			if (loggerFactory != null)
			{
				logger = loggerFactory.Create(typeof(FormHelper));
			}

			var config = (IMonoRailConfiguration)provider.GetService(typeof(IMonoRailConfiguration));

			if (config != null)
			{
				var jsLibConfig = config.JSGeneratorConfiguration.DefaultLibrary;

				if (jsLibConfig != null)
				{
					if (jsLibConfig.BrowserValidatorProvider != null)
					{
						ValidatorProvider = (IBrowserValidatorProvider)
							Activator.CreateInstance(jsLibConfig.BrowserValidatorProvider);
					}
				}
			}

			ValidatorRegistry = (IValidatorRegistry)provider.GetService(typeof(IValidatorRegistry));

			if (ValidatorRegistry != null)
			{
				ValidatorRunner = new ValidatorRunner(false, ValidatorRegistry);
			}
			else
			{
				ValidatorRunner = new ValidatorRunner(false, new CachedValidationRegistry());
			}
		}
Exemple #11
0
		private void Initialize()
		{
			ValidatorRegistry = new CachedValidationRegistry();
			ValidatorRunner = new ValidatorRunner(false, ValidatorRegistry);
			ValidatorProvider = new PrototypeWebValidator();
		}
		public IValidator[] GetValidators(ValidatorRunner validatorRunner, Type targetType, PropertyInfo property, RunWhen runWhen)
		{
			throw new NotSupportedException();
		}
		/// <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));
		}
Exemple #14
0
        public ActionResult Login(string username, string password, string redirectUrl)
        {
            var loginData = new LoginData(username, password);

            var validationRunner = new ValidatorRunner(new CachedValidationRegistry());

            if (!validationRunner.IsValid(loginData))
            {
                AddErrorMessages(validationRunner.GetErrorSummary(loginData).ErrorMessages);
                return RedirectToAction("Login");
            }

            if (!authenticationService.SignIn(username, password))
            {
                AddErrorMessage("Invalid Login");
                return RedirectToAction("Login");
            }

            if (redirectUrl != null)
                return Redirect(redirectUrl);

            return RedirectToAction("Index", "Account");
        }
		/// <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;
		}
 public void AccountInformation([DataBind("Register")] AccountInformationViewModel viewModel)
 {
     ValidatorRunner runner = new ValidatorRunner(new CachedValidationRegistry());
     if (runner.IsValid(viewModel))
     {
         Session["AccountInfo"] = viewModel;
         RedirectToAction("PersonalInformation");
     }
     else
     {
         var summary = runner.GetErrorSummary(viewModel);
         Flash["summary"] = summary;
         Flash["Register"] = viewModel;
     }
 }
Exemple #17
0
        public ActionResult Register(RegistrationData registrationData)
        {
            var validationRunner = new ValidatorRunner(new CachedValidationRegistry());

            if (!validationRunner.IsValid(registrationData))
            {
                // there were errors, report them back to the user
                foreach (var errorMessage in validationRunner.GetErrorSummary(registrationData).ErrorMessages)
                    AddErrorMessage(errorMessage);

                TempData.Add(registrationData);
                return RedirectToAction("Register");
            }

            Member member = memberService.GetByUsername(registrationData.UserName);

            if (member != null)
            {
                userSession.PushUserMessage(FlashMessage.MessageType.Error, "A user with that username already exists, please try again");
                TempData.Add(registrationData);
                return RedirectToAction("Register");
            }

            member = new Member
                         {
                             Username = registrationData.UserName,
                             Email = registrationData.Email,
                             PasswordSalt = cryptographer.CreateSalt(),
                             FirstName = registrationData.FirstName,
                             LastName = registrationData.LastName
                         };

            member.Password = cryptographer.Hash(registrationData.Password, member.PasswordSalt);

            memberService.Add(member);

            authenticator.SignIn(member);

            return RedirectToAction("Index");
        }
		/// <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;
		}
 public void PersonalInformation([DataBind("Personal")] PersonalInformationViewModel viewModel)
 {
     Flash["categories"] = Category.All;
     var runner = new ValidatorRunner(new CachedValidationRegistry());
     if (runner.IsValid(viewModel))
     {
         Session["PersonalInfo"] = viewModel;
         RedirectToAction("Thanks");
     }
     else
     {
         Flash["Personal"] = viewModel;
         Flash["summary"] = runner.GetErrorSummary(viewModel);
     }
 }
Exemple #20
0
		/// <summary>
		/// Initializes this instance. Implementors 
		/// can use this method to perform initialization
		/// </summary>
		protected virtual void Initialize()
		{
			IValidatorRegistry validatorRegistry = 
				(IValidatorRegistry) serviceProvider.GetService(typeof(IValidatorRegistry));

			validator = CreateValidatorRunner(validatorRegistry);
		}
        protected void OnSaveButtonClicked (object sender, System.EventArgs e)
        {
            mycase.Name = nameEntry.Text;
            mycase.start_date = startDateSelector.SelectedDate ();
            mycase.StartDateType = startDateSelector.SelectedDateType ();
            mycase.AffectedPeople = System.Convert.ToInt32(affectedPeople.Text);

            mycase.end_date = endDateSelector.SelectedDate ();
            mycase.EndDateType = endDateSelector.SelectedDateType ();

            mycase.NarrativeDescription = description.Text;
            mycase.Summary = summary.Text;
            mycase.Observations = observations.Text;

            if (mycase.IsValid())
            {
                mycase.SaveAndFlush ();
                this.IsEditing = false;
                if (CaseSaved != null)
                    CaseSaved (mycase, e);
            } else {
                ResourceManager mgr = new ResourceManager("Castle.Components.Validator.Messages", Assembly.GetAssembly(typeof(Castle.Components.Validator.CachedValidationRegistry)));
                var runner = new ValidatorRunner(new CachedValidationRegistry(mgr));
                if (runner.IsValid(mycase) || !runner.HasErrors(mycase)) return;
                //var summary = runner.GetErrorSummary(mycase);

                Console.WriteLine( String.Join(",", mycase.ValidationErrorMessages) );
                new ValidationErrorsDialog (mycase.PropertiesValidationErrorMessages, (Gtk.Window)this.Toplevel);
            }
        }
		/// <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();
		}