Search in sources :

Example 1 with FieldError

use of org.springframework.validation.FieldError in project head by mifos.

the class SavingsProductFormValidator method validate.

@SuppressWarnings({ "ThrowableInstanceNeverThrown" })
@Override
public void validate(Object target, Errors errors) {
    SavingsProductFormBean formBean = (SavingsProductFormBean) target;
    if (formBean.getGeneralDetails().getName().trim().isEmpty()) {
        errors.reject("NotEmpty.generalDetails.name");
    }
    if (formBean.getGeneralDetails().getDescription().length() > 200) {
        errors.reject("Size.generalDetails.description");
    }
    if (formBean.getGeneralDetails().getShortName().trim().isEmpty()) {
        errors.reject("NotEmpty.generalDetails.shortName");
    }
    if (formBean.getGeneralDetails().getSelectedCategory().trim().isEmpty()) {
        errors.reject("NotEmpty.generalDetails.selectedCategory");
    }
    if (null == formBean.getGeneralDetails().getStartDateDay() || 1 > formBean.getGeneralDetails().getStartDateDay() || 31 < formBean.getGeneralDetails().getStartDateDay()) {
        errors.reject("Min.generalDetails.startDateDay");
    }
    if (null == formBean.getGeneralDetails().getStartDateMonth() || 1 > formBean.getGeneralDetails().getStartDateMonth() || 12 < formBean.getGeneralDetails().getStartDateMonth()) {
        errors.reject("Min.generalDetails.startDateMonth");
    }
    if (null == formBean.getGeneralDetails().getStartDateAsDateTime() || !(formBean.getGeneralDetails().getStartDateYear().length() == 4)) {
        errors.reject("Min.generalDetails.startDate");
    } else {
        MutableDateTime nextYear = new MutableDateTime();
        nextYear.setDate(new Date().getTime());
        nextYear.addYears(1);
        if (formBean.getGeneralDetails().getStartDateAsDateTime() != null && formBean.getGeneralDetails().getStartDateAsDateTime().compareTo(nextYear) > 0) {
            errors.reject("Min.generalDetails.startDate");
        }
    }
    if ((null != formBean.getGeneralDetails().getEndDateDay() || null != formBean.getGeneralDetails().getEndDateMonth() || null != formBean.getGeneralDetails().getEndDateMonth()) && formBean.getGeneralDetails().getEndDateAsDateTime() == null) {
        errors.reject("Min.generalDetails.endDate");
    }
    if (formBean.getGeneralDetails().getStartDateAsDateTime() != null && formBean.getGeneralDetails().getEndDateAsDateTime() != null && formBean.getGeneralDetails().getStartDateAsDateTime().compareTo(formBean.getGeneralDetails().getEndDateAsDateTime()) > 0) {
        errors.reject("Min.generalDetails.endDate");
    }
    if (formBean.getGeneralDetails().getSelectedApplicableFor().trim().isEmpty()) {
        errors.reject("NotEmpty.generalDetails.selectedApplicableFor");
    }
    if (formBean.getSelectedDepositType().trim().isEmpty()) {
        errors.reject("NotEmpty.savingsProduct.selectedDepositType");
    } else if (formBean.isMandatory() && (null == formBean.getAmountForDeposit() || formBean.getAmountForDeposit() <= 0)) {
        errors.reject("Min.savingsProduct.amountForDesposit");
    }
    if (formBean.isGroupSavingAccount() && formBean.getSelectedGroupSavingsApproach().trim().isEmpty()) {
        errors.reject("NotEmpty.savingsProduct.selectedGroupSavingsApproach");
    }
    if (!formBean.isInterestRateZero()) {
        if (null == formBean.getInterestRate() || formBean.getInterestRate().doubleValue() < 1.0 || formBean.getInterestRate().doubleValue() > 100.0 || errorProcessor.getRejectedValue("interestRate") != null) {
            if (errorProcessor.getTarget() == null) {
                errors.reject("NotNull.savingsProduct.interestRate");
            } else {
                BindException bindException = new BindException(errorProcessor.getTarget(), errorProcessor.getObjectName());
                bindException.addError(new FieldError(errorProcessor.getObjectName(), "interestRate", errorProcessor.getRejectedValue("interestRate"), true, new String[] { "NotNull.savingsProduct.interestRate" }, null, null));
                errors.addAllErrors(bindException);
            }
        }
        if (formBean.getSelectedInterestCalculation().trim().isEmpty()) {
            errors.reject("NotEmpty.savingsProduct.selectedInterestCalculation");
        }
        if (null == formBean.getInterestCalculationFrequency() || formBean.getInterestCalculationFrequency() < 1 || errorProcessor.getRejectedValue("interestCalculationFrequency") != null) {
            if (errorProcessor.getTarget() == null) {
                errors.reject("NotNull.savingsProduct.interestCalculationFrequency");
            } else {
                BindException bindException = new BindException(errorProcessor.getTarget(), errorProcessor.getObjectName());
                bindException.addError(new FieldError(errorProcessor.getObjectName(), "interestCalculationFrequency", errorProcessor.getRejectedValue("interestCalculationFrequency"), true, new String[] { "NotNull.savingsProduct.interestCalculationFrequency" }, null, null));
                errors.addAllErrors(bindException);
            }
        }
        if (null == formBean.getInterestPostingMonthlyFrequency() || formBean.getInterestPostingMonthlyFrequency() < 1 || errorProcessor.getRejectedValue("interestPostingMonthlyFrequency") != null) {
            if (errorProcessor.getTarget() == null) {
                errors.reject("Min.savingsProduct.interestPostingMonthlyFrequency");
            } else {
                BindException bindException = new BindException(errorProcessor.getTarget(), errorProcessor.getObjectName());
                bindException.addError(new FieldError(errorProcessor.getObjectName(), "interestPostingMonthlyFrequency", errorProcessor.getRejectedValue("interestPostingMonthlyFrequency"), true, new String[] { "Min.savingsProduct.interestPostingMonthlyFrequency" }, null, null));
                errors.addAllErrors(bindException);
            }
        }
    }
    BigDecimal minBalanceForInterestCalculation;
    try {
        minBalanceForInterestCalculation = BigDecimal.valueOf(Double.valueOf(formBean.getMinBalanceRequiredForInterestCalculation()));
    } catch (NumberFormatException e) {
        minBalanceForInterestCalculation = new BigDecimal("-1");
    }
    if (minBalanceForInterestCalculation.compareTo(BigDecimal.ZERO) < 0) {
        errors.reject("Min.savingsProduct.balanceRequiredForInterestCalculation");
    }
    if (formBean.getSelectedPrincipalGlCode().trim().isEmpty()) {
        errors.reject("NotEmpty.savingsProduct.selectedPrincipalGlCode");
    }
    if (formBean.getSelectedInterestGlCode().trim().isEmpty()) {
        errors.reject("NotEmpty.savingsProduct.selectedInterestGlCode");
    }
    Short digsAfterDec = configurationServiceFacade.getAccountingConfiguration().getDigitsAfterDecimal();
    Short digsBeforeDec = configurationServiceFacade.getAccountingConfiguration().getDigitsBeforeDecimal();
    Double maxWithdrawalObj = formBean.getMaxWithdrawalAmount();
    String maxWithdrawalString;
    if (maxWithdrawalObj == null) {
        maxWithdrawalString = "";
    } else {
        maxWithdrawalString = maxWithdrawalObj.toString();
    }
    int dot = maxWithdrawalString.lastIndexOf('.');
    int max = digsAfterDec + digsBeforeDec + dot;
    int withdrawalLength = maxWithdrawalString.length();
    if (maxWithdrawalString.lastIndexOf(0, dot) > digsBeforeDec) {
        errors.reject("MaxDigitsBefore.savingProduct.withdrawal", new String[] { digsBeforeDec.toString() }, null);
    }
    if (maxWithdrawalString.lastIndexOf(dot, withdrawalLength) > digsAfterDec) {
        errors.reject("MaxDigitsAfter.savingProduct.withdrawal", new String[] { digsAfterDec.toString() }, null);
    }
    if (withdrawalLength > max) {
        errors.reject("MaxDigitsNumber.savingProduct.withdrawal", new String[] { String.valueOf(max) }, null);
    }
    Double amountForDepositObj = formBean.getAmountForDeposit();
    String amountForDepositString;
    if (amountForDepositObj == null) {
        amountForDepositString = "";
    } else {
        amountForDepositString = amountForDepositObj.toString();
    }
    int depositLength = amountForDepositString.length();
    if (amountForDepositString.lastIndexOf(0, dot) > digsBeforeDec) {
        errors.reject("MaxDigitsBefore.savingProduct.deposit", new String[] { digsBeforeDec.toString() }, null);
    }
    if (amountForDepositString.lastIndexOf(dot, depositLength) > digsAfterDec) {
        errors.reject("MaxDigitsAfter.savingProduct.deposit", new String[] { digsAfterDec.toString() }, null);
    }
    if (depositLength > max) {
        errors.reject("MaxDigitsNumber.savingProduct.deposit", new String[] { String.valueOf(max) }, null);
    }
}
Also used : MutableDateTime(org.joda.time.MutableDateTime) BindException(org.springframework.validation.BindException) FieldError(org.springframework.validation.FieldError) Date(java.util.Date) BigDecimal(java.math.BigDecimal)

Example 2 with FieldError

use of org.springframework.validation.FieldError in project spring-framework by spring-projects.

the class SpringValidatorAdapter method processConstraintViolations.

/**
	 * Process the given JSR-303 ConstraintViolations, adding corresponding errors to
	 * the provided Spring {@link Errors} object.
	 * @param violations the JSR-303 ConstraintViolation results
	 * @param errors the Spring errors object to register to
	 */
protected void processConstraintViolations(Set<ConstraintViolation<Object>> violations, Errors errors) {
    for (ConstraintViolation<Object> violation : violations) {
        String field = determineField(violation);
        FieldError fieldError = errors.getFieldError(field);
        if (fieldError == null || !fieldError.isBindingFailure()) {
            try {
                ConstraintDescriptor<?> cd = violation.getConstraintDescriptor();
                String errorCode = determineErrorCode(cd);
                Object[] errorArgs = getArgumentsForConstraint(errors.getObjectName(), field, cd);
                if (errors instanceof BindingResult) {
                    // Can do custom FieldError registration with invalid value from ConstraintViolation,
                    // as necessary for Hibernate Validator compatibility (non-indexed set path in field)
                    BindingResult bindingResult = (BindingResult) errors;
                    String nestedField = bindingResult.getNestedPath() + field;
                    if ("".equals(nestedField)) {
                        String[] errorCodes = bindingResult.resolveMessageCodes(errorCode);
                        bindingResult.addError(new ObjectError(errors.getObjectName(), errorCodes, errorArgs, violation.getMessage()));
                    } else {
                        Object rejectedValue = getRejectedValue(field, violation, bindingResult);
                        String[] errorCodes = bindingResult.resolveMessageCodes(errorCode, field);
                        bindingResult.addError(new FieldError(errors.getObjectName(), nestedField, rejectedValue, false, errorCodes, errorArgs, violation.getMessage()));
                    }
                } else {
                    // got no BindingResult - can only do standard rejectValue call
                    // with automatic extraction of the current field value
                    errors.rejectValue(field, errorCode, errorArgs, violation.getMessage());
                }
            } catch (NotReadablePropertyException ex) {
                throw new IllegalStateException("JSR-303 validated property '" + field + "' does not have a corresponding accessor for Spring data binding - " + "check your DataBinder's configuration (bean property versus direct field access)", ex);
            }
        }
    }
}
Also used : BindingResult(org.springframework.validation.BindingResult) ObjectError(org.springframework.validation.ObjectError) NotReadablePropertyException(org.springframework.beans.NotReadablePropertyException) FieldError(org.springframework.validation.FieldError)

Example 3 with FieldError

use of org.springframework.validation.FieldError in project grails-core by grails.

the class GrailsDomainClassValidator method validatePropertyWithConstraint.

@SuppressWarnings("rawtypes")
private void validatePropertyWithConstraint(String propertyName, Object obj, Errors errors, BeanWrapper bean, Map constrainedProperties) {
    int i = propertyName.lastIndexOf(".");
    String constrainedPropertyName;
    if (i > -1) {
        constrainedPropertyName = propertyName.substring(i + 1, propertyName.length());
    } else {
        constrainedPropertyName = propertyName;
    }
    FieldError fieldError = errors.getFieldError(constrainedPropertyName);
    if (fieldError == null) {
        ConstrainedProperty c = (ConstrainedProperty) constrainedProperties.get(constrainedPropertyName);
        c.setMessageSource(messageSource);
        c.validate(obj, bean.getPropertyValue(constrainedPropertyName), errors);
    }
}
Also used : FieldError(org.springframework.validation.FieldError) GString(groovy.lang.GString) ConstrainedProperty(grails.validation.ConstrainedProperty)

Example 4 with FieldError

use of org.springframework.validation.FieldError in project grails-core by grails.

the class AbstractConstraintTests method testConstraintMessageCodes.

protected void testConstraintMessageCodes(Constraint constraint, Object value, String[] code, Object[] args) {
    Errors errors = testConstraintFailed(constraint, value);
    FieldError fieldError = errors.getFieldError(constraint.getPropertyName());
    for (int j = 0; j < code.length; j++) {
        checkCode(fieldError, code[j]);
    }
    checkArguments(args, fieldError.getArguments());
}
Also used : Errors(org.springframework.validation.Errors) FieldError(org.springframework.validation.FieldError)

Example 5 with FieldError

use of org.springframework.validation.FieldError in project grails-core by grails.

the class AbstractConstraintTests method testConstraintMessageCode.

protected void testConstraintMessageCode(Constraint constraint, Object value, String code, Object[] args) {
    Errors errors = testConstraintFailed(constraint, value);
    FieldError fieldError = errors.getFieldError(constraint.getPropertyName());
    checkCode(fieldError, code);
    checkArguments(args, fieldError.getArguments());
}
Also used : Errors(org.springframework.validation.Errors) FieldError(org.springframework.validation.FieldError)

Aggregations

FieldError (org.springframework.validation.FieldError)92 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)20 ObjectError (org.springframework.validation.ObjectError)19 Test (org.junit.jupiter.api.Test)17 BindingResult (org.springframework.validation.BindingResult)16 ApiOperation (io.swagger.annotations.ApiOperation)14 BeanPropertyBindingResult (org.springframework.validation.BeanPropertyBindingResult)12 Errors (org.springframework.validation.Errors)11 ArrayList (java.util.ArrayList)7 BindException (org.springframework.validation.BindException)6 CustomResult (com.megagao.production.ssm.domain.customize.CustomResult)5 Locale (java.util.Locale)5 Test (org.junit.Test)5 ExceptionHandler (org.springframework.web.bind.annotation.ExceptionHandler)5 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)5 JsonResult (com.odysseusinc.arachne.commons.api.v1.dto.util.JsonResult)4 HashMap (java.util.HashMap)4 UserProfileDTO (com.odysseusinc.arachne.portal.api.v1.dto.UserProfileDTO)3 LinkedHashSet (java.util.LinkedHashSet)3 MapBindingResult (org.springframework.validation.MapBindingResult)3