List of usage examples for org.springframework.validation FieldError getCodes
@Override
@Nullable
public String[] getCodes()
From source file:jetx.ext.springmvc.SpringMvcFunctions.java
/** * ??//from w w w.java 2s . c om */ public static List<String> fieldErrors(JetPageContext ctx, String fieldName) { Errors errors = FunctionUtils.findErrors(ctx.getContext()); if (errors == null) { return EMPTY_STRING_LIST; } List<FieldError> fes = errors.getFieldErrors(fieldName); List<String> msgs = new ArrayList<String>(0); for (FieldError fe : fes) { String[] codes = fe.getCodes(); String defaultMsg = fe.getDefaultMessage(); Object[] args = fe.getArguments(); Locale locale = getLocale(ctx); MessageSource ms = getMessageSource(ctx); if (codes == null || codes.length == 0 || ms == null) { msgs.add(defaultMsg); } else { String msg = null; for (int i = 0; i < codes.length; i++) { try { msg = ms.getMessage(codes[i], args, locale); } catch (NoSuchMessageException e) { // } if (msg == null) { msg = defaultMsg; } } msgs.add(msg); } } return Collections.unmodifiableList(msgs); }
From source file:ch.ralscha.extdirectspring.bean.ExtDirectFormPostResult.java
private void addErrors(Locale locale, MessageSource messageSource, BindingResult bindingResult) { if (bindingResult != null && bindingResult.hasFieldErrors()) { Map<String, String> errorMap = new HashMap<String, String>(); for (ObjectError objectError : bindingResult.getAllErrors()) { FieldError fieldError = (FieldError) objectError; String message = null; for (String code : fieldError.getCodes()) { message = MessageUtil.getMessage(code, null, locale); // , new Object[] {(fieldError.getObjectName() +"." + fieldError.getField()), fieldError.getRejectedValue()} if (StringUtils.isNotBlank(message)) { break; }/*from w ww . j av a 2 s .c o m*/ } errorMap.put(fieldError.getField(), StringUtils.defaultIfBlank(message, fieldError.getDefaultMessage())); } if (errorMap.isEmpty()) { addResultProperty("success", true); } else { addResultProperty("errors", errorMap); addResultProperty("success", false); } } else { setSuccess(true); } // if (bindingResult != null && bindingResult.hasFieldErrors()) { // Map<String, List<String>> errorMap = new HashMap<String, List<String>>(); // for (FieldError fieldError : bindingResult.getFieldErrors()) { // String message = fieldError.getDefaultMessage(); // if (messageSource != null) { // Locale loc = (locale != null ? locale : Locale.getDefault()); // message = messageSource.getMessage(fieldError.getCode(), fieldError.getArguments(), loc); // } // List<String> fieldErrors = errorMap.get(fieldError.getField()); // // if (fieldErrors == null) { // fieldErrors = new ArrayList<String>(); // errorMap.put(fieldError.getField(), fieldErrors); // } // // fieldErrors.add(message); // } // if (errorMap.isEmpty()) { // addResultProperty("success", true); // } else { // addResultProperty("errors", errorMap); // addResultProperty("success", false); // } // } else { // setSuccess(true); // } }
From source file:com.tapas.evidence.fe.form.EvidenceForm.java
public boolean validate(final MetaModel metaModel, final Validator validator, final Model model, final IUiMessageSource messageSource, final Locale locale) { boolean result = false; final BindingResult validationResult = new BeanPropertyBindingResult(model, model.getClass().getName()); clearFields(metaModel);/*w w w . ja v a2 s . co m*/ validator.validate(model, validationResult); if (validationResult.hasErrors()) { for (FieldError error : validationResult.getFieldErrors()) { final String field = error.getField(); final String message = getMessage(error.getCodes(), messageSource, locale); final Field fieldComponent = this.getField(field); if (fieldComponent instanceof AbstractField) { ((AbstractField) fieldComponent).setComponentError(new UserError(message)); } } result = false; } else { result = true; } return result; }
From source file:com.asual.summer.core.ErrorResolver.java
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {/* ww w .ja v a 2s .c o m*/ if (e instanceof BindException) { BindException be = (BindException) e; Map<String, Map<String, Object>> errors = new HashMap<String, Map<String, Object>>(); for (FieldError fe : (List<FieldError>) be.getFieldErrors()) { Map<String, Object> error = new HashMap<String, Object>(); Object[] args = fe.getArguments(); String key = fe.isBindingFailure() ? fe.getCodes()[2].replaceFirst("typeMismatch", "conversion") : "validation." + fe.getCodes()[2]; String message = ResourceUtils.getMessage(key, args); if (message == null) { if (!fe.isBindingFailure()) { if (key.split("\\.").length > 3) { message = ResourceUtils .getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)) + key.substring(key.lastIndexOf(".")), args); } if (message == null && key.split("\\.").length > 2) { message = ResourceUtils .getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)), args); } } else if (fe.isBindingFailure() && key.split("\\.").length > 2) { message = ResourceUtils.getMessage( key.substring(0, key.indexOf(".")) + key.substring(key.lastIndexOf(".")), args); } else { message = fe.getDefaultMessage(); } } error.put("message", message != null ? message : "Error (" + key + ")"); error.put("value", fe.getRejectedValue()); errors.put(fe.getField(), error); } for (ObjectError oe : (List<ObjectError>) be.getGlobalErrors()) { Map<String, Object> error = new HashMap<String, Object>(); Object[] args = oe.getArguments(); String key = "global" + (oe.getCodes() != null ? "." + oe.getCodes()[2] : ""); String message = ResourceUtils.getMessage(key, args); if (message == null) { if (key.split("\\.").length > 3) { message = ResourceUtils.getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)) + key.substring(key.lastIndexOf(".")), args); } if (message == null && key.split("\\.").length > 2) { message = ResourceUtils.getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)), args); } if (message == null) { message = oe.getDefaultMessage(); } } error.put("message", message != null ? message : "Error (" + key + ")"); error.put("value", oe.getObjectName()); errors.put(oe.getObjectName(), error); } String form = (String) RequestUtils.getParameter("_form"); if (form != null) { if (request.getAttribute(ERRORS) == null) { request.setAttribute(ERRORS, errors); request.setAttribute(be.getObjectName(), be.getTarget()); return new ModelAndView(new InternalResourceView( form.concat(form.contains("?") ? "&" : "?").concat("_error=true"))); } } else { List<String> pairs = new ArrayList<String>(); for (String key : errors.keySet()) { pairs.add(key + "=" + errors.get(key).get("message")); } try { response.sendError(HttpServletResponse.SC_BAD_REQUEST, StringUtils.join(pairs, ";")); } catch (IOException ioe) { logger.error(ioe.getMessage(), ioe); } } } return null; }
From source file:com.vmware.bdd.rest.advice.RestValidationErrorHandler.java
private ValidationError getError(FieldError fieldError) { ValidationError error = new ValidationError(); error.setPrimaryCode(fieldError.getCodes()[0]); String localizedErrorMessage = messageSource.getMessage(fieldError, LocaleContextHolder.getLocale()); error.setMessage(localizedErrorMessage); return error; }
From source file:org.mifos.clientportfolio.loan.ui.LoanAccountFormBean.java
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = { "SIC_INNER_SHOULD_BE_STATIC_ANON" }, justification = "") public void validateEnterAccountDetailsStep(ValidationContext context) { MessageContext messageContext = context.getMessageContext(); Errors errors = validator.checkConstraints(this); // handle data binding errors that may of occurred if (messageContext.hasErrorMessages()) { Message[] errorMessages = messageContext.getMessagesByCriteria(new MessageCriteria() { @Override/*w w w . ja v a 2 s . c o m*/ public boolean test(@SuppressWarnings("unused") Message message) { return true; } }); messageContext.clearMessages(); for (Message message : errorMessages) { handleDataMappingError(errors, message); } } if (this.glimApplicable) { int index = 0; int selectedCount = 0; for (Boolean clientSelected : this.clientSelectForGroup) { if (clientSelected != null && clientSelected.booleanValue()) { Number clientAmount = this.clientAmount[index]; if (clientAmount == null || exceedsMinOrMax(clientAmount, Integer.valueOf(1), this.maxAllowedAmount)) { String defaultErrorMessage = "Please specify valid Amount."; rejectGlimClientAmountField(index + 1, errors, defaultErrorMessage); } if (clientAmount != null) { BigDecimal amountAsDecimal = new BigDecimal(clientAmount.toString()).stripTrailingZeros(); int places = amountAsDecimal.scale(); if (places > this.digitsAfterDecimalForMonetaryAmounts) { String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.client.amount.digitsAfterDecimal.invalid", new Object[] { index + 1, this.digitsAfterDecimalForMonetaryAmounts }); } int digitsBefore = amountAsDecimal.toBigInteger().toString().length(); if (digitsBefore > this.digitsBeforeDecimalForMonetaryAmounts) { String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.client.amount.digitsBeforeDecimal.invalid", new Object[] { index + 1, this.digitsBeforeDecimalForMonetaryAmounts }); } } // check error message of loan purpose for each client when its mandatory.. Integer clientLoanPurposeId = this.clientLoanPurposeId[index]; if (this.purposeOfLoanMandatory && isInvalidSelection(clientLoanPurposeId)) { errors.rejectValue("clientLoanPurposeId", "loanAccountFormBean.glim.purposeOfLoan.invalid", new Object[] { index + 1 }, "Please specify loan purpose."); this.clientLoanPurposeId[index] = 0; } else { // needed so attempt in freemarker(ftl) to display loan purpose doesnt fall over. if (clientLoanPurposeId == null) { this.clientLoanPurposeId[index] = 0; } } selectedCount++; } else { Number clientAmount = this.clientAmount[index]; Integer clientLoanPurposeId = this.clientLoanPurposeId[index]; if (clientAmount != null || clientLoanPurposeId != null) { String defaultErrorMessage = "You have entered details for a member you have not selected. Select the checkbox in front of the member's name in order to include him or her in the loan."; rejectUnselectedGlimClientAmountField(index + 1, errors, defaultErrorMessage); } } index++; } if (selectedCount < 2) { String defaultErrorMessage = "Not enough clients for group loan."; rejectGroupLoanWithTooFewClients(errors, defaultErrorMessage); } } if (this.amount == null || exceedsMinOrMax(this.amount, this.minAllowedAmount, this.maxAllowedAmount)) { String defaultErrorMessage = "Please specify valid Amount."; if (glimApplicable) { defaultErrorMessage = "The sum of the amounts specified for each member is outside the allowable total amount for this loan product."; rejectGlimTotalAmountField(errors, defaultErrorMessage); } else { rejectAmountField(errors, defaultErrorMessage); } } if (this.amount != null) { BigDecimal amountAsDecimal = new BigDecimal(this.amount.toString()).stripTrailingZeros(); int places = amountAsDecimal.scale(); if (places > this.digitsAfterDecimalForMonetaryAmounts) { String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.amount.digitsAfterDecimal.invalid", new Object[] { this.digitsAfterDecimalForMonetaryAmounts }); } int digitsBefore = amountAsDecimal.toBigInteger().toString().length(); if (digitsBefore > this.digitsBeforeDecimalForMonetaryAmounts) { String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.amount.digitsBeforeDecimal.invalid", new Object[] { this.digitsBeforeDecimalForMonetaryAmounts }); } } if (this.interestRate == null || exceedsMinOrMax(this.interestRate, this.minAllowedInterestRate, this.maxAllowedInterestRate)) { String defaultErrorMessage = "Please specify valid Interest rate."; rejectInterestRateField(errors, defaultErrorMessage); } if (this.interestRate != null) { BigDecimal interestRateAsDecimal = new BigDecimal(this.interestRate.toString()).stripTrailingZeros(); int places = interestRateAsDecimal.scale(); if (places > this.digitsAfterDecimalForInterest) { String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.digitsAfterDecimalForInterest.invalid", new Object[] { this.digitsAfterDecimalForInterest }); } int digitsBefore = interestRateAsDecimal.toBigInteger().toString().length(); if (digitsBefore > this.digitsBeforeDecimalForInterest) { String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.digitsBeforeDecimalForInterest.invalid", new Object[] { this.digitsBeforeDecimalForInterest }); } } if (this.numberOfInstallments == null || exceedsMinOrMax(this.numberOfInstallments, this.minNumberOfInstallments, this.maxNumberOfInstallments)) { String defaultErrorMessage = "Please specify valid number of installments."; rejectNumberOfInstallmentsField(errors, defaultErrorMessage); } if (this.graceDuration == null || this.graceDuration.intValue() < 0) { if (!errors.hasFieldErrors("graceDuration")) { String defaultErrorMessage = "Please specify valid Grace period for repayments. Grace period should be a value less than " + numberOfInstallments.intValue() + "."; rejectGraceDurationField(errors, defaultErrorMessage); } } else { if (this.graceDuration.intValue() > this.maxGraceDuration.intValue()) { String defaultErrorMessage = "The Grace period cannot be greater than in loan product definition."; errors.rejectValue("graceDuration", "loanAccountFormBean.gracePeriodDuration.invalid", defaultErrorMessage); } if (this.numberOfInstallments != null && (this.graceDuration.intValue() >= this.numberOfInstallments.intValue())) { String defaultErrorMessage = "Grace period for repayments must be less than number of loan installments."; errors.rejectValue("graceDuration", "loanAccountFormBean.gracePeriodDurationInRelationToInstallments.invalid", defaultErrorMessage); } } if (dateValidator == null) { dateValidator = new DateValidator(); } if (!dateValidator.formsValidDate(this.disbursementDateDD, this.disbursementDateMM, this.disbursementDateYY)) { String defaultErrorMessage = "Please specify valid disbursal date."; rejectDisbursementDateField(errors, defaultErrorMessage, "disbursementDateDD", "loanAccountFormBean.DisbursalDate.invalid", ""); } else { LocalDate validDate = new DateTime().withDate(disbursementDateYY.intValue(), disbursementDateMM.intValue(), disbursementDateDD.intValue()).toLocalDate(); org.mifos.platform.validations.Errors disbursementDateErrors = new org.mifos.platform.validations.Errors(); if (this.redoLoanAccount) { disbursementDateErrors = loanDisbursementDateValidationServiceFacade .validateLoanWithBackdatedPaymentsDisbursementDate(validDate, customerId, productId); } else { disbursementDateErrors = loanDisbursementDateValidationServiceFacade .validateLoanDisbursementDate(validDate, customerId, productId); } for (ErrorEntry entry : disbursementDateErrors.getErrorEntries()) { String defaultErrorMessage = "The disbursal date is invalid."; rejectDisbursementDateField(errors, defaultErrorMessage, "disbursementDateDD", entry.getErrorCode(), entry.getArgs().get(0)); } } if (this.sourceOfFundsMandatory && isInvalidSelection(this.fundId)) { errors.rejectValue("fundId", "loanAccountFormBean.SourceOfFunds.invalid", "Please specify source of funds."); } if (this.externalIdMandatory && StringUtils.isBlank(this.externalId)) { errors.rejectValue("externalId", "loanAccountFormBean.externalid.invalid", "Please specify required external id."); } if (!this.glimApplicable && this.purposeOfLoanMandatory && isInvalidSelection(this.loanPurposeId)) { errors.rejectValue("loanPurposeId", "loanAccountFormBean.PurposeOfLoan.invalid", "Please specify loan purpose."); } validateAdministrativeAndAdditionalFees(errors); if (this.repaymentScheduleIndependentOfCustomerMeeting) { if (isInvalidRecurringFrequency(this.repaymentRecursEvery)) { errors.rejectValue("repaymentRecursEvery", "loanAccountFormBean.repaymentDay.recursEvery.invalid", "Please specify a valid recurring frequency for repayment day."); } if (this.weekly) { if (isInvalidDayOfWeekSelection()) { errors.rejectValue("repaymentDayOfWeek", "loanAccountFormBean.repaymentDay.weekly.dayOfWeek.invalid", "Please select a day of the week for repayment day."); } } else if (this.monthly) { if (this.monthlyDayOfMonthOptionSelected) { if (isInvalidDayOfMonthEntered()) { errors.rejectValue("repaymentDayOfMonth", "loanAccountFormBean.repaymentDay.monthly.dayOfMonth.invalid", "Please select a day of the month for repayment day."); } } else if (this.monthlyWeekOfMonthOptionSelected) { if (isInvalidWeekOfMonthSelection()) { errors.rejectValue("repaymentWeekOfMonth", "loanAccountFormBean.repaymentDay.monthly.weekOfMonth.invalid", "Please select a week of the month for repayment day."); } if (isInvalidDayOfWeekSelection()) { errors.rejectValue("repaymentDayOfWeek", "loanAccountFormBean.repaymentDay.monthly.dayOfWeek.invalid", "Please select a day of the week for repayment day."); } } } if (this.variableInstallmentsAllowed) { if (this.selectedFeeId != null) { for (Number feeId : this.selectedFeeId) { if (feeId != null) { VariableInstallmentWithFeeValidationResult result = variableInstallmentsFeeValidationServiceFacade .validateFeeCanBeAppliedToVariableInstallmentLoan(feeId.longValue()); if (!result.isFeeCanBeAppliedToVariableInstallmentLoan()) { errors.rejectValue("selectedFeeId", "loanAccountFormBean.additionalfees.variableinstallments.invalid", new String[] { result.getFeeName() }, "This type of fee cannot be applied to loan with variable installments."); } } } } int defaultFeeIndex = 0; if (this.defaultFeeId != null) { for (Number feeId : this.defaultFeeId) { if (feeId != null) { Boolean feeSelectedForRemoval = this.defaultFeeSelected[defaultFeeIndex]; if (feeSelectedForRemoval == null || !feeSelectedForRemoval) { VariableInstallmentWithFeeValidationResult result = variableInstallmentsFeeValidationServiceFacade .validateFeeCanBeAppliedToVariableInstallmentLoan(feeId.longValue()); if (!result.isFeeCanBeAppliedToVariableInstallmentLoan()) { errors.rejectValue("selectedFeeId", "loanAccountFormBean.defaultfees.variableinstallments.invalid", new String[] { result.getFeeName() }, "This type of fee cannot be applied to loan with variable installments."); } } } defaultFeeIndex++; } } } } if (errors.hasErrors()) { for (FieldError fieldError : errors.getFieldErrors()) { MessageBuilder builder = new MessageBuilder().error().source(fieldError.getField()) .codes(fieldError.getCodes()).defaultText(fieldError.getDefaultMessage()) .args(fieldError.getArguments()); messageContext.addMessage(builder.build()); } } }