//ValidateWithConfim (Email, Password) public void ValidateWithConfim(System.Web.Mvc.ModelStateDictionary modelState) { ValidationCheck.CheckErrors(this, modelState, true); //check Login if (!ValidationCheck.IsEmpty(this.Login) && !ProjectConfig.Config.DataProvider.GetInstance().UserRepository.ValidateLogin(this.Login, ID)) { modelState.AddModelError("Login", "Login already exists. Please enter a different user name."); } //check Email if (!ValidationCheck.IsEmpty(this.Email) && !ProjectConfig.Config.DataProvider.GetInstance().UserRepository.ValidateEmail(this.Email, ID)) { modelState.AddModelError("Email", "A username for that e-mail address already exists. Please enter a different e-mail address."); } // check Email and Confirm Email if (!String.Equals(this.Email, this.ConfirmEmail, StringComparison.Ordinal)) { modelState.AddModelError("Email", "The Email and confirmation Email do not match."); modelState.AddModelError("ConfirmEmail", ""); } // check Password and Confirm Password if (!String.Equals(this.Password, this.ConfirmPassword, StringComparison.Ordinal)) { modelState.AddModelError("Password", "The password and confirmation password do not match."); modelState.AddModelError("ConfirmPassword", ""); } }
public static void DumpErrors(this System.Web.Mvc.ModelStateDictionary ModelState) { var errors = from key in ModelState let errorList = ModelState[key.Key].Errors where errorList.Any() select new { Item = key.Key, Value = key.Value, errorList }; foreach (var errorList in errors) { System.Diagnostics.Debug.WriteLine("MODEL ERROR:"); System.Diagnostics.Debug.WriteLine(errorList.Item); System.Diagnostics.Debug.WriteLine(errorList.Value); foreach (var error in errorList.errorList) { System.Diagnostics.Debug.WriteLine(error.ErrorMessage); System.Diagnostics.Debug.WriteLine(error.Exception); } System.Diagnostics.Debug.WriteLine("-----"); } }
public void validCliente(Cliente client, System.Web.Mvc.ModelStateDictionary modelState) { modelState.Clear(); if (string.IsNullOrEmpty(client.Nombre)) { modelState.AddModelError("Nombre", "El campo nombre es obligatorio!"); } if (string.IsNullOrEmpty(client.Dni)) { modelState.AddModelError("Dni", "El campo DNI es obligatorio!"); return; } if (string.IsNullOrEmpty(client.Direccion)) { modelState.AddModelError("Direccion", "La direccion es obligatoria!"); } if (!isValidNombreC(client.Nombre)) { modelState.AddModelError("Nombre", "El nombre no debe tener caracteres especiales!"); } if (!isCorrectDniC(client.Dni)) { modelState.AddModelError("Dni", "El DNI no debe tener caracteres especiales!"); return; } if (existeUserC(client.Dni)) { modelState.AddModelError("Dni", "Otro cliente tiene el mismo DNI!"); } }
public static List <string> toJson(this System.Web.Mvc.ModelStateDictionary models) { var errorList = (from item in models where item.Value.Errors.Any() select item.Value.Errors[0].ErrorMessage).ToList(); return(errorList); }
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"); } }
public void Validate(System.Web.Mvc.ModelStateDictionary modelState) { ValidationCheck.CheckErrors(this, modelState); if (!ValidationCheck.IsEmpty(this.Email) && ValidationCheck.IsEmail(this.Email)) { IUser user = ProjectConfig.DataProvider.UserRepository.GetUserByEmail(Email, false); if (user == null) { modelState.AddModelError("Email", "Sorry, the e-mail address entered was not found. Please try again."); } } }
public static string GetModelStateErrors(this System.Web.Mvc.ModelStateDictionary modelState) { var result = string.Empty; foreach (System.Web.Mvc.ModelState modelStateValue in modelState.Values) { foreach (System.Web.Mvc.ModelError error in modelStateValue.Errors) { result += error.ErrorMessage; } } return(result); }
public virtual bool ValidateOrder(ModelStateDictionary modelState, CheckoutViewModel viewModel, IDictionary <ILineItem, IList <ValidationIssue> > validationMessages) { PurchaseValidation validation; if (viewModel.IsAuthenticated) { validation = AuthenticatedPurchaseValidation; } else { validation = AnonymousPurchaseValidation; } return(validation.ValidateModel(modelState, viewModel) && validation.ValidateOrderOperation(modelState, validationMessages)); }
public void SendingMissingValueRequest() { var form = new System.Collections.Specialized.NameValueCollection(); form.Add("txtTags", "Tag9"); form.Add("txtAnswer", "Answer9"); var modelState = new System.Web.Mvc.ModelStateDictionary(); var response = Wispero.Web.Binders.QnAModelBinder.BindQnAModel(form, modelState); Assert.IsNotNull(response); Assert.IsInstanceOfType(response, typeof(QuestionAndAnswerModel)); Assert.IsTrue(modelState.Count == 1); Assert.IsTrue(modelState["Question"].Errors.Count > 0); }
//ValidateWithoutConfim public void ValidateWithoutConfim(System.Web.Mvc.ModelStateDictionary modelState) { ValidationCheck.CheckErrors(this, modelState, true); //check Login if (!ValidationCheck.IsEmpty(this.Login) && !ProjectConfig.Config.DataProvider.GetInstance().UserRepository.ValidateLogin(this.Login, ID)) { modelState.AddModelError("Login", "Login already exists. Please enter a different user name."); } //check Email if (!ValidationCheck.IsEmpty(this.Email) && !ProjectConfig.Config.DataProvider.GetInstance().UserRepository.ValidateEmail(this.Email, ID)) { modelState.AddModelError("Email", "A username for that e-mail address already exists. Please enter a different e-mail address."); } }
public void Validate(System.Web.Mvc.ModelStateDictionary modelState) { ValidationCheck.CheckErrors(this, modelState); if (!String.Equals(this.NewPassword, this.ConfirmPassword, StringComparison.Ordinal)) { modelState.AddModelError("NewPassword", "The new password and confirmation password do not match"); modelState.AddModelError("ConfirmPassword", ""); } SessionUser cuser = AppHelper.CurrentUser; if (!ProjectConfig.DataProvider.UserRepository.ValidatePasswordForUser(this.CurrentPassword, cuser != null ? cuser.ID : 0)) { modelState.AddModelError("CurrentPassword", "Current password is invalid"); } }
public void validVend(Vendedor vend, System.Web.Mvc.ModelStateDictionary modelState) { modelState.Clear(); if (string.IsNullOrEmpty(vend.Nombre)) { modelState.AddModelError("Nombre", "Campo nombre obligatorio!"); } if (string.IsNullOrEmpty(vend.ApPaterno)) { modelState.AddModelError("ApPaterno", "Campo ApPaterno obligatorio!"); } if (string.IsNullOrEmpty(vend.ApMaterno)) { modelState.AddModelError("ApMaterno", "Campo ApMaterno obligatorio!"); } if (string.IsNullOrEmpty(vend.Dni)) { modelState.AddModelError("Dni", "Campo DNI obligatorio!"); } if (string.IsNullOrEmpty(vend.Pass)) { modelState.AddModelError("Pass", "Campo Pass obligatorio!"); return; } if (!isValidNombre(vend.Nombre)) { modelState.AddModelError("Nombre", "El nombre no debe tener caracteres especiales!"); } if (!isValidNombre(vend.ApPaterno)) { modelState.AddModelError("ApPaterno", "El ApPaterno no debe tener caracteres especiales!"); } if (!isValidNombre(vend.ApMaterno)) { modelState.AddModelError("ApMaterno", "El ApMaterno no debe tener caracteres especiales!"); } if (!isCorrectDni(vend.Dni)) { modelState.AddModelError("Dni", "El DNI no debe tener caracteres especiales!"); return; } if (existeUser(vend.Dni)) { modelState.AddModelError("Dni", "Ya existe el mismo DNI!"); } }
public void ValidateModel(System.Web.Mvc.ModelStateDictionary modelState) { try { ApplicationDBContext db = new ApplicationDBContext(); if (this.StartDate != null) { if (this.StartDate > this.EndDate) { modelState.AddModelError("StartDate", ResourceMessage.Startdate); } } } catch (Exception ex) { throw ex; } }
public void validarProducto(ProductoAux producto, System.Web.Mvc.ModelStateDictionary modelState) { modelState.Clear(); if (string.IsNullOrEmpty(producto.Nombre)) { modelState.AddModelError("Nombre", "El nombre es campo obligatorio!"); } //var duplicado = db.Productos.Any(a => a.Nombre == producto.Nombre); //if (duplicado) //{ // modelState.AddModelError("Nombre", " El producto ya existe en la base de datos !"); //} //else //{ // db.SaveChanges(); //} if (string.IsNullOrEmpty(producto.Stock)) { modelState.AddModelError("Stock", "El stock es campo obligatorio!"); } if (string.IsNullOrEmpty(producto.Precio)) { modelState.AddModelError("Precio", "El precio es campo obligatorio!"); } if (string.IsNullOrEmpty(producto.UnidadMedida)) { modelState.AddModelError("UnidadMedida", "La unidad de medida es campo obligatorio!"); return; } if (!isValidNumber(producto.Precio)) { modelState.AddModelError("Precio", "El precio no debe tener caracteres espciales!"); } }
private static bool VerifyValueUsability(ControllerContext controllerContext, ModelStateDictionary modelState, string modelStateKey, Type elementType, object value) { if (value == null && !TypeHelpers.TypeAllowsNullValue(elementType)) { if (modelState.IsValidField(modelStateKey)) { // a required entry field was left blank string message = GetValueRequiredResource(controllerContext); modelState.AddModelError(modelStateKey, message); } // we don't care about "you must enter a value" messages if there was an error return(false); } return(true); }
/// <summary> /// 获取第一个错误。 /// </summary> /// <param name="modelState">一个 <see cref="System.Web.Mvc.ModelStateDictionary"/>。</param> /// <returns>返回一个 null 值,或首个错误的内容。</returns> public static string FirstError(this ModelStateDictionary modelState) => modelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).FirstOrDefault();
public Result Verify(ServiceRuleFunc <bool> ServiceRuleFunc, ModelStateDictionary modelState, object RuleFactory) { throw new NotImplementedException(); }
/// <summary> /// 获取所有错误,默认以“\n”合并。 /// </summary> /// <param name="modelState">一个 <see cref="System.Web.Mvc.ModelStateDictionary"/>。</param> /// <param name="separator">分隔符。</param> /// <returns>返回错误的合并内容。</returns> public static string AllErrors(this ModelStateDictionary modelState, string separator = null) => string.Join(separator ?? AllErrorsJoinSeparator, modelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));
public static IEnumerable <string> GetErrorsFromModelState(this System.Web.Mvc.ModelStateDictionary ModelState) { return(ModelState.SelectMany(x => x.Value.Errors.Select(error => error.ErrorMessage))); }
/// <summary> /// 重置操作参数文本框的值 /// </summary> /// <param name="modelState"></param> public static void Reset(ModelStateDictionary modelState) { modelState["OpType"].Value = new ValueProviderResult(OperationType.Null, "0", CultureInfo.CurrentCulture); }
public bool Save(ModelStateDictionary ModelState) { throw new NotImplementedException(); }
public Result Save(ModelStateDictionary ModelState, IClientInfo clientInfo) { throw new NotImplementedException(); }
public virtual IPurchaseOrder PlaceOrder(ICart cart, ModelStateDictionary modelState, CheckoutViewModel checkoutViewModel) { try { if (cart.GetFirstForm().Payments.FirstOrDefault(x => x.IsVippsPayment()) != null) { cart.Properties[VippsConstants.VippsPaymentTypeField] = VippsPaymentType.CHECKOUT; } var paymentProcessingResults = cart.ProcessPayments(_paymentProcessor, _orderGroupCalculator).ToList(); if (paymentProcessingResults.Any(r => !r.IsSuccessful)) { modelState.AddModelError("", _localizationService.GetString("/Checkout/Payment/Errors/ProcessingPaymentFailure") + string.Join(", ", paymentProcessingResults.Select(p => p.Message))); return(null); } var redirectPayment = paymentProcessingResults.FirstOrDefault(r => !string.IsNullOrEmpty(r.RedirectUrl)); if (redirectPayment != null) { checkoutViewModel.RedirectUrl = redirectPayment.RedirectUrl; return(null); } var processedPayments = cart.GetFirstForm().Payments.Where(x => x.Status.Equals(PaymentStatus.Processed.ToString())).ToList(); if (!processedPayments.Any()) { // Return null in case there is no payment was processed. return(null); } var totalProcessedAmount = processedPayments.Sum(x => x.Amount); if (totalProcessedAmount != cart.GetTotal(_orderGroupCalculator).Amount) { throw new InvalidOperationException("Wrong amount"); } PurchaseValidation validation; if (checkoutViewModel.IsAuthenticated) { validation = AuthenticatedPurchaseValidation; } else { validation = AnonymousPurchaseValidation; } if (!validation.ValidateOrderOperation(modelState, _cartService.RequestInventory(cart))) { return(null); } var orderReference = _orderRepository.SaveAsPurchaseOrder(cart); var purchaseOrder = _orderRepository.Load <IPurchaseOrder>(orderReference.OrderGroupId); _orderRepository.Delete(cart.OrderLink); return(purchaseOrder); } catch (PaymentException ex) { modelState.AddModelError("", _localizationService.GetString("/Checkout/Payment/Errors/ProcessingPaymentFailure") + ex.Message); } return(null); }
public Result Verify(ModelStateDictionary ModelState) { throw new NotImplementedException(); }
private static UI.TreeDataSourceResult CreateTreeDataSourceResult <TModel, T1, T2, TResult>(this IQueryable queryable, UI.DataSourceRequest request, Expression <Func <TModel, T1> > idSelector, Expression <Func <TModel, T2> > parentIDSelector, System.Web.Mvc.ModelStateDictionary modelState, Func <TModel, TResult> selector, Expression <Func <TModel, bool> > rootSelector) { var result = new UI.TreeDataSourceResult(); IQueryable source = queryable; List <IFilterDescriptor> list = new List <IFilterDescriptor>(); if (request.Filters != null) { list.AddRange(request.Filters); } if (list.Any <IFilterDescriptor>()) { source = source.Where(list).ParentsRecursive <TModel>(queryable, idSelector, parentIDSelector); } IQueryable allData = source; if (rootSelector != null) { source = source.Where(rootSelector); } List <SortDescriptor> list2 = new List <SortDescriptor>(); if (request.Sorts != null) { list2.AddRange(request.Sorts); } List <AggregateDescriptor> list3 = new List <AggregateDescriptor>(); if (request.Aggregates != null) { list3.AddRange(request.Aggregates); } if (list3.Any <AggregateDescriptor>()) { IQueryable queryable4 = source; foreach (IGrouping <T2, TModel> grouping in queryable4.GroupBy(parentIDSelector)) { result.AggregateResults.Add(Convert.ToString(grouping.Key), grouping.AggregateForLevel <TModel, T1, T2>(allData, list3, idSelector, parentIDSelector)); } } if (list2.Any <SortDescriptor>()) { source = source.Sort(list2); } result.Data = source.Execute <TModel, TResult>(selector); if ((modelState != null) && !modelState.IsValid) { result.Errors = modelState.SerializeErrors(); } return(result); }
private static void AddValueRequiredMessageToModelState(ControllerContext controllerContext, ModelStateDictionary modelState, string modelStateKey, Type elementType, object value) { if (value == null && !TypeHelpers.TypeAllowsNullValue(elementType) && modelState.IsValidField(modelStateKey)) { modelState.AddModelError(modelStateKey, GetValueRequiredResource(controllerContext)); } }
public JsonResult JsonInputErrorsMessage(object valModel, System.Web.Mvc.ModelStateDictionary valModelStateErrors) { return(Json(new { success = false, data = valModel, errors = valModelStateErrors.Values.Where(i => i.Errors.Count > 0) })); }
public static void SetValue(this System.Web.Mvc.ModelStateDictionary state, string key, object value) { state.SetModelValue(key, new ValueProviderResult(value, value.ToString(), CultureInfo.CurrentCulture)); }
public static string GetModelStateErrors(this ModelStateDictionary modelState) { var errorMsgs = modelState.Values.SelectMany(t => t.Errors.Select(a => a.ErrorMessage)); return(string.Join(";", errorMsgs)); }
/// <summary> /// Cria o resultado da origem de dados. /// </summary> /// <typeparam name="TModel">Tipo da model.</typeparam> /// <typeparam name="TResult">Tipo do resultado.</typeparam> /// <param name="queryable">Consulta.</param> /// <param name="request">Requisição.</param> /// <param name="modelState">Estado do modelo.</param> /// <param name="selector">Seletor.</param> /// <returns></returns> private static Colosoft.Web.Mvc.UI.DataSourceResult CreateDataSourceResult <TModel, TResult>(this IQueryable queryable, Mvc.UI.DataSourceRequest request, System.Web.Mvc.ModelStateDictionary modelState, Func <TModel, TResult> selector) { Func <AggregateDescriptor, IEnumerable <AggregateFunction> > func = null; Action <GroupDescriptor> action = null; Action <GroupDescriptor> action2 = null; var result = new Mvc.UI.DataSourceResult(); IQueryable source = queryable; var filters = new List <IFilterDescriptor>(); if (request.Filters != null) { filters.AddRange(request.Filters); } if (filters.Any()) { source = source.Where(filters); } var sorts = new List <SortDescriptor>(); if (request.Sorts != null) { sorts.AddRange(request.Sorts); } var temporarySortDescriptors = new List <SortDescriptor>(); var instance = new List <GroupDescriptor>(); if (request.Groups != null) { instance.AddRange <GroupDescriptor>(request.Groups); } var aggregates = new List <AggregateDescriptor>(); if (request.Aggregates != null) { aggregates.AddRange(request.Aggregates); } if (aggregates.Any()) { IQueryable queryable3 = source.AsQueryable(); IQueryable queryable4 = queryable3; if (filters.Any()) { queryable4 = queryable3.Where(filters); } if (func == null) { func = a => a.Aggregates; } result.AggregateResults = queryable4.Aggregate(aggregates.SelectMany(func)); if (instance.Any() && aggregates.Any()) { if (action == null) { action = delegate(GroupDescriptor g) { foreach (var a in aggregates) { g.AggregateFunctions.AddRange(a.Aggregates); } }; } instance.Each(action); } } result.Total = source.Count(); if (!sorts.Any() && queryable.Provider.IsEntityFrameworkProvider()) { var descriptor = new SortDescriptor { Member = queryable.ElementType.FirstSortableProperty() }; sorts.Add(descriptor); temporarySortDescriptors.Add(descriptor); } if (instance.Any()) { if (action2 == null) { action2 = delegate(GroupDescriptor groupDescriptor) { var item = new SortDescriptor { Member = groupDescriptor.Member, SortDirection = groupDescriptor.SortDirection }; sorts.Insert(0, item); temporarySortDescriptors.Add(item); }; } instance.Reverse <GroupDescriptor>().Each <GroupDescriptor>(action2); } if (sorts.Any()) { source = source.Sort(sorts); } IQueryable notPagedData = source; source = source.Page(request.Page - 1, request.PageSize); if (instance.Any()) { source = source.GroupBy(notPagedData, instance); } result.Data = source.Execute <TModel, TResult>(selector); if ((modelState != null) && !modelState.IsValid) { result.Errors = modelState.SerializeErrors(); } temporarySortDescriptors.Each(sortDescriptor => sorts.Remove(sortDescriptor)); return(result); }