예제 #1
0
 public void SetModelStateError(System.Web.Mvc.ModelStateDictionary modelState)
 {
     if (!string.IsNullOrEmpty(error))
     {
         modelState.AddModelError("error", error);
     }
 }
 /// <summary>
 /// Adiciona uma mensagem de valor requerido para o estado da model.
 /// </summary>
 /// <param name="controllerContext"></param>
 /// <param name="modelState"></param>
 /// <param name="modelStateKey"></param>
 /// <param name="elementType"></param>
 /// <param name="value"></param>
 private static void AddValueRequiredMessageToModelState(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelStateDictionary modelState, string modelStateKey, Type elementType, object value)
 {
     if (((value == null) && !TypeHelpers.TypeAllowsNullValue(elementType)) && modelState.IsValidField(modelStateKey))
     {
         modelState.AddModelError(modelStateKey, GetValueRequiredResource(controllerContext));
     }
 }
예제 #3
0
        /// <inheritDoc/>
        public virtual void ValidateProfileData(ProfileEditViewModel viewModel, System.Web.Mvc.ModelStateDictionary modelState)
        {
            List <ProfileBindingsContract> profileBindingsList = this.GetDeserializedProfileBindings();

            foreach (var profile in this.SelectedUserProfiles)
            {
                var readOnlyFields  = string.IsNullOrEmpty(profile.User.ExternalProviderName) ? new string[0] : UserManager.GetReadOnlyFields(profile.GetType().Name, profile.User.ExternalProviderName);
                var profileBindings = profileBindingsList.SingleOrDefault(p => p.ProfileType == profile.GetType().FullName);
                if (profileBindings != null)
                {
                    var requiredProperties = profileBindings.Properties.Where(p => p.Required);

                    foreach (var prop in requiredProperties)
                    {
                        if (readOnlyFields.Any(x => x.Equals(prop.Name, StringComparison.OrdinalIgnoreCase)))
                        {
                            // skip validation for read-only fields
                            continue;
                        }

                        string propValue;

                        if (!viewModel.Profile.TryGetValue(prop.Name, out propValue) || string.IsNullOrWhiteSpace(propValue))
                        {
                            modelState.AddModelError(string.Format("Profile[{0}]", prop.Name), string.Format(Res.Get <ProfileResources>().RequiredProfileField, prop.Name));
                        }
                    }
                }
            }

            var minPassLength = UserManager.GetManager(this.MembershipProvider).MinRequiredPasswordLength;

            if (!string.IsNullOrEmpty(viewModel.OldPassword) && !string.IsNullOrEmpty(viewModel.NewPassword) && !string.IsNullOrEmpty(viewModel.RepeatPassword))
            {
                if (viewModel.NewPassword.Length < minPassLength)
                {
                    modelState.AddModelError("NewPassword", string.Format(Res.Get <ProfileResources>().MinimumPasswordLength, minPassLength));
                }

                if (viewModel.RepeatPassword.Length < minPassLength)
                {
                    modelState.AddModelError("RepeatPassword", string.Format(Res.Get <ProfileResources>().MinimumPasswordLength, minPassLength));
                }
            }
        }
예제 #4
0
        public void Validate(System.Web.Mvc.ModelStateDictionary modelState)
        {
            ValidationCheck.CheckErrors(this, modelState);
            if (String.IsNullOrEmpty(Email))
            {
                modelState.AddModelError("Email", "<br /><br /><br /><br />Please enter your email address");
            }

            if (!ValidationCheck.IsEmpty(this.Email) && !ProjectConfig.DataProvider.UserRepository.ValidateOuterSubscriptionEmail(this.Email, ID))
            {
                modelState.AddModelError("Email", "<br /><br /><br /><br />This email already present in system");
            }

            if (this.Email != this.EmailConfirm)
            {
                modelState.AddModelError("Email", "<br /><br /><br /><br />Email and confirmation email should be match.");
            }
        }
예제 #5
0
 public virtual void CopyErrorsToModelState(System.Web.Mvc.ModelStateDictionary ModelState)
 {
     if (Errors.Any())
     {
         foreach (var err in Errors)
         {
             ModelState.AddModelError(err.PropertyName, err.ErrorMessage);
         }
     }
 }
예제 #6
0
 public static void Validate(this AddEditContentViewModel model, ProviderPortalEntities db,
                             System.Web.Mvc.ModelStateDictionary modelState)
 {
     if (model.ContentId == 0)
     {
         if (!ContentManager.IsPathValid(model.Path))
         {
             modelState.AddModelError("Path",
                                      AppGlobal.Language.GetText("SiteContent_Error_InvalidPath",
                                                                 "Please specify a valid path."));
         }
     }
     if (model.UserContext == UserContext.UserContextName.None)
     {
         modelState.AddModelError("UserContext",
                                  AppGlobal.Language.GetText("SiteContent_Error_SelectAContext",
                                                             "Select one or more user contexts to make this content available in."));
     }
 }
예제 #7
0
 /// <summary>
 /// Pobranie informacji o błędach bazodanowych na podstawie stanu modelu
 /// </summary>
 /// <param name="ex">Wyjątek</param>
 /// <param name="ModelState">Stan modelu</param>
 /// <param name="prefix">Prefiks określający nazwę właściwości modelu dla której sprawdzane są błędy</param>
 public static void ModelHandleException(Exception ex, System.Web.Mvc.ModelStateDictionary ModelState, string prefix)
 {
     if (ex is System.Data.Entity.Validation.DbEntityValidationException)
     {
         using (DbValidationErrorHandler dvValExp = new DbValidationErrorHandler(ex as System.Data.Entity.Validation.DbEntityValidationException))
         {
             if (dvValExp.HasErrors)
             {
                 foreach (var err in dvValExp.ValidationErrors)
                 {
                     ModelState.AddModelError(prefix + "." + err.Property, err.Message);
                 }
             }
         }
     }
     else
     {
         ModelState.AddModelError("", ex.Message);
     }
 }
예제 #8
0
 public static void CopyToModelState(this RuleException re,
                                     System.Web.Mvc.ModelStateDictionary modelState, string prefix)
 {
     foreach (string key in re.Errors)
     {
         foreach (string value in re.Errors.GetValues(key))
         {
             modelState.AddModelError(prefix + "." + key, value);
         }
     }
 }
        public void Validate(System.Web.Mvc.ModelStateDictionary modelState)
        {
            ValidationCheck.CheckErrors(this, modelState);

            //check Email
            if (!ValidationCheck.IsEmpty(this.Email) && !ProjectConfig.DataProvider.DifferentRepository.ValidateOuterSubscriptionEmail(this.Email, ID))
            {
                modelState.AddModelError("Email", "This email already present in system");
            }

            if (!(this.Email == this.EmailConfirm))
            {
                modelState.AddModelError("Email", "Email and confirmation email should be match.");
            }

            if (!IsRecievingWeeklySpecials && !IsRecievingUpdates)
            {
                modelState.AddModelError("IsRecievingUpdates", "Select to recieve news and updates or/and weekly specials.");
            }
        }
        public static bool Validate <TModel, TValidator>(TModel model, TValidator validator,
                                                         System.Web.Mvc.ModelStateDictionary modelState)
            where TValidator : AbstractValidator <TModel>
        {
            ValidationResult result = validator.Validate(model);

            foreach (var error in result.Errors)
            {
                modelState.AddModelError(error.PropertyName, error.ErrorMessage);
            }

            return(result.IsValid);
        }
예제 #11
0
        public static void AddModelErrors(this ModelStateDictionary modelState, IEnumerable <ValidationResult> validationResults, string defaultErrorKey = null)
        {
            if (validationResults == null)
            {
                return;
            }

            foreach (var validationResult in validationResults)
            {
                var key = validationResult.MemberNames.FirstOrDefault() ?? defaultErrorKey ?? string.Empty;
                modelState.AddModelError(key, validationResult.ErrorMessage);
            }
        }
예제 #12
0
        public static void CheckErrors(object model, System.Web.Mvc.ModelStateDictionary modelState, bool validateNotUpdateedFields)
        {
            Dictionary <string, List <ValidationRule> > errorRules = ValidationCheck.GetValidationRules(model.GetType());

            foreach (KeyValuePair <string, List <ValidationRule> > item in errorRules)
            {
                object obj = model.GetType().InvokeMember(item.Key, BindingFlags.GetProperty, null, model, null);

                foreach (ValidationRule rule in item.Value)
                {
                    if (!rule.IFieldValidation.Validate(obj))
                    {
                        if (modelState.ContainsKey(rule.FieldName) || validateNotUpdateedFields)
                        {
                            modelState.AddModelError(rule.FieldName, rule.IFieldValidation.GetErrorMessage(rule.FieldTitle));
                        }
                        continue;
                    }
                }
            }
        }
 public static void AddModelError(this System.Web.Mvc.ModelStateDictionary modelState, string error, params object[] formatArgs)
 {
     modelState.AddModelError(string.Empty, error.FormatWith(formatArgs));
 }
예제 #14
0
        public void Validate(System.Web.Mvc.ModelStateDictionary modelState)
        {
            ValidationCheck.CheckErrors(this, modelState);

            //check Login
            if (!ValidationCheck.IsEmpty(this.Login) && !ProjectConfig.Config.DataProvider.GetInstance().UserRepository.ValidateLogin(this.Login, ID))
            {
                modelState.AddModelError("Login", "This login already present in system");
            }

            //check Email
            if (!ValidationCheck.IsEmpty(this.Email) && !ProjectConfig.Config.DataProvider.GetInstance().UserRepository.ValidateEmail(this.Email, ID))
            {
                modelState.AddModelError("Email", "This email already present in system");
            }

            if (!String.Equals(this.Email, this.ConfirmEmail, StringComparison.Ordinal))
            {
                modelState.AddModelError("Email", "The Email and confirmation Email do not match.");
                modelState.AddModelError("ConfirmEmail", "");
            }

            if (!String.Equals(this.Password, this.ConfirmPassword, StringComparison.Ordinal))
            {
                modelState.AddModelError("Password", "The password and confirmation password do not match.");
                modelState.AddModelError("ConfirmPassword", "");
            }

            if (!ProjectConfig.Config.DataProvider.GetInstance().UserRepository.CheckChangePassword(this.ID, this.Password))
            {
                modelState.AddModelError("Password", "Need to change and confirmation the password.");
                modelState.AddModelError("ConfirmPassword", "");
            }

            if (!Agree)
            {
                modelState.AddModelError("Agree", "YOU MUST CHECK THE BOX BELOW");
            }

            StringBuilder sb = new StringBuilder(BillingPhone);

            sb.Replace("(", "").Replace(")", "").Replace("-", "").Replace("_", "").Replace(" ", "").Replace("x", "");
            BillingPhone = sb.ToString();

            sb = new StringBuilder(BillingWorkPhone);
            sb.Replace("(", "").Replace(")", "").Replace("-", "").Replace("_", "").Replace(" ", "").Replace("x", "");
            BillingWorkPhone = sb.ToString();

            sb = new StringBuilder(ShippingPhone);
            sb.Replace("(", "").Replace(")", "").Replace("-", "").Replace("_", "").Replace(" ", "").Replace("x", "");
            ShippingPhone = sb.ToString();

            sb = new StringBuilder(ShippingWorkPhone);
            sb.Replace("(", "").Replace(")", "").Replace("-", "").Replace("_", "").Replace(" ", "").Replace("x", "");
            ShippingWorkPhone = sb.ToString();

            if (String.IsNullOrWhiteSpace(BillingPhone))
            {
                modelState.AddModelError("BillingPhone", "The Phone number is required");
            }

            if (String.IsNullOrWhiteSpace(ShippingPhone) && !BillingLikeShipping)
            {
                modelState.AddModelError("ShippingPhone", "The Phone number is required");
            }

            //if ((modelState.ContainsKey("BillingPhone1") && modelState["BillingPhone1"].Errors.Count > 0) || (modelState.ContainsKey("BillingPhone2") && modelState["BillingPhone2"].Errors.Count > 0))
            //  modelState.AddModelError("BillingPhone", "Phone should contain digits only");
            //if ((modelState.ContainsKey("BillingWorkPhone1") && modelState["BillingWorkPhone1"].Errors.Count > 0) || (modelState.ContainsKey("BillingWorkPhone2") && modelState["BillingWorkPhone2"].Errors.Count > 0))
            //  modelState.AddModelError("BillingWorkPhone", "Work Phone should contain digits only");

            //if ((modelState.ContainsKey("ShippingPhone1") && modelState["ShippingPhone1"].Errors.Count > 0))
            //  modelState.AddModelError("ShippingPhone", "Phone should contain digits only");
            //if ((modelState.ContainsKey("ShippingWorkPhone1") && modelState["ShippingWorkPhone1"].Errors.Count > 0) || (modelState.ContainsKey("ShippingWorkPhone2") && modelState["ShippingWorkPhone2"].Errors.Count > 0))
            //  modelState.AddModelError("ShippingWorkPhone", "Work Phone should contain digits only");
        }
예제 #15
0
 //remark: developers use for show exceptions in "controller"
 public static void AddModelHandledError(this System.Web.Mvc.ModelStateDictionary modelState, string key, string errorMessage)
 {
     modelState.AddModelError(key, errorMessage);
     modelState.AddModelError("isHandled", "true");
 }
        public static void ConvertCodeToMsg(System.Web.Mvc.ModelStateDictionary modelState, Dictionary <string, ErrorCodes> MessageCodes)
        {
            foreach (KeyValuePair <string, ErrorCodes> dict in MessageCodes)
            {
                ErrorCodes code = dict.Value;
                switch (code)
                {
                case ErrorCodes.IsRequired:
                    modelState.AddModelError(dict.Key, "Is Required!");
                    break;

                case ErrorCodes.DoesNotExist:
                    modelState.AddModelError(dict.Key, "Does not exist.");
                    break;

                case ErrorCodes.ExistsAlready:
                    modelState.AddModelError(dict.Key, "Is already in use.");
                    break;

                case ErrorCodes.InvalidRange:
                    modelState.AddModelError(dict.Key, "Invalid range.");
                    break;

                case ErrorCodes.NotANumber:
                    modelState.AddModelError(dict.Key, "Not a number.");
                    break;

                case ErrorCodes.NotValidPageNr:
                    modelState.AddModelError(dict.Key, "Not a valid page number.");
                    break;

                case ErrorCodes.TooLong:
                    modelState.AddModelError(dict.Key, "Too long.");
                    break;

                case ErrorCodes.MoreThanFiveHundredChars:
                    modelState.AddModelError(dict.Key, "Too long, cannot be longer than 500 characters.");
                    break;

                case ErrorCodes.MoreThanFiftyChars:
                    modelState.AddModelError(dict.Key, "Too long, cannot be longer than 50 characters.");
                    break;

                case ErrorCodes.InsufficentPermission:
                    modelState.AddModelError(dict.Key, "Insufficent permission.");
                    break;

                case ErrorCodes.PasswordDoesNotMatch:
                    modelState.AddModelError(dict.Key, "Password must be between 5-25 characters. Have at least 1 upper and lower case chararacter, and at least one number.");
                    break;

                case ErrorCodes.WrongPassword:
                    modelState.AddModelError(dict.Key, "Wrong Password.");
                    break;

                case ErrorCodes.BooksExistInClassification:
                    modelState.AddModelError(dict.Key, "You can not delete a classification that has books assigned to it.");
                    break;

                case ErrorCodes.MustBeOnlyNumbers:
                    modelState.AddModelError(dict.Key, "Must contain only numbers 0-9.");
                    break;

                default:
                    modelState.AddModelError(dict.Key, "Unspecified error code: " + code.ToString() + " Please contact the development team.");
                    break;
                }
            }
        }
 public static void AddModelError(this System.Web.Mvc.ModelStateDictionary modelState, string error)
 {
     modelState.AddModelError(string.Empty, error);
 }
 public static void AddModelError(this System.Web.Mvc.ModelStateDictionary modelState, string key, Result result)
 {
     result.ErrorMessages.ForEach(r => modelState.AddModelError(key, r));
 }
예제 #19
0
        protected void Validate(object x, object father, string propertyName, string currPrefix)
        {
            if (x == null)
            {
                return;
            }
            if (x is IConvertible)
            {
                if (father == null)
                {
                    return;
                }
                ValidationContext ctx = new ValidationContext(father, null, null);
                ctx.MemberName = propertyName;
                List <ValidationResult> errors = new List <ValidationResult>();
                bool success = Validator.TryValidateProperty(x, ctx, errors);
                if (!success)
                {
                    foreach (ValidationResult vs in errors)
                    {
                        modelState.AddModelError(currPrefix, vs.ErrorMessage);
                    }
                }
            }
            else if (x is IEnumerable)
            {
                int i = 0;
                foreach (object y in x as IEnumerable)
                {
                    Validate(y, null, null,
                             currPrefix +
                             string.Format("[{0}]", i)
                             );
                    i++;
                }
            }
            else
            {
                Type currType = x.GetType();
                if (currType.IsClass)
                {
                    List <ValidationResult> errors = new List <ValidationResult>();
                    bool success = Validator.TryValidateObject(x, new ValidationContext(x, null, null), errors, true);
                    ValidationAttribute[] attrs = currType.GetCustomAttributes(typeof(ValidationAttribute), true) as ValidationAttribute[];

                    foreach (ValidationAttribute attr in attrs)
                    {
                        ValidationResult vs = attr.GetValidationResult(x, new ValidationContext(x, null, null));
                        if (vs != null && vs != ValidationResult.Success)
                        {
                            modelState.AddModelError(currPrefix, vs.ErrorMessage);
                        }
                    }

                    foreach (PropertyInfo prop in currType.GetProperties())
                    {
                        if ((prop.PropertyType == typeof(DateTime) || prop.PropertyType == typeof(DateTime?)) && prop.CanRead && prop.CanWrite)
                        {
                            object dateVal = prop.GetValue(x, new object[0]);
                            if (dateVal != null)
                            {
                                prop.SetValue(x, ((DateTime)dateVal).ToLocalTime(), new object[0]);
                            }
                        }
                        Validate(prop.GetValue(x, new object[0]),
                                 x,
                                 prop.Name,
                                 BasicHtmlHelper.AddField(currPrefix, prop.Name));
                    }
                }
            }
        }
예제 #20
0
        public void Validate(System.Web.Mvc.ModelStateDictionary modelState)
        {
            ValidationCheck.CheckErrors(this, modelState);

            //check Login
            if (!ValidationCheck.IsEmpty(this.Login) && !ProjectConfig.Config.DataProvider.GetInstance().UserRepository.ValidateLogin(this.Login, ID))
            {
                modelState.AddModelError("Login", "This login already present in system");
            }

            //check Email
            if (!ValidationCheck.IsEmpty(this.Email) && !ProjectConfig.Config.DataProvider.GetInstance().UserRepository.ValidateEmail(this.Email, ID))
            {
                modelState.AddModelError("Email", "This email already present in system");
            }

            if (!String.Equals(this.Password, this.ConfirmPassword, StringComparison.Ordinal))
            {
                modelState.AddModelError("Password", "The password and confirmation password do not match.");
                modelState.AddModelError("ConfirmPassword", "");
            }

            if (!String.Equals(this.Email, this.ConfirmEmail, StringComparison.Ordinal))
            {
                modelState.AddModelError("Email", "The email and confirmation email do not match.");
                modelState.AddModelError("ConfirmEmail", "");
            }

            if (this.BillingState == "--" && this.BillingCountry == 1)
            {
                modelState.AddModelError("BillingState", "'State' is required");
            }

            if (this.ShippingState == "--" && this.ShippingCountry == 1 && !this.BillingLikeShipping)
            {
                modelState.AddModelError("ShippingState", "'State' is required");
            }

            if (this.BillingState != "--" && this.BillingCountry > 1)
            {
                modelState.AddModelError("BillingState", "'State' must have value '--'");
            }

            if (this.ShippingState != "--" && this.ShippingCountry > 1 && !this.BillingLikeShipping)
            {
                modelState.AddModelError("ShippingState", "'State' must have value '--'");
            }
            if (this.BillingState == "--" && this.BillingCountry > 1 && String.IsNullOrEmpty(this.BillingInternationalState))
            {
                modelState.AddModelError("BillingInternationalState", "'International State' is required");
            }
            if (this.ShippingState == "--" && this.ShippingCountry > 1 && String.IsNullOrEmpty(this.ShippingInternationalState) && !this.BillingLikeShipping)
            {
                modelState.AddModelError("ShippingInternationalState", "'International State' is required");
            }
        }