Example usage for org.springframework.validation FieldError getDefaultMessage

List of usage examples for org.springframework.validation FieldError getDefaultMessage

Introduction

In this page you can find the example usage for org.springframework.validation FieldError getDefaultMessage.

Prototype

@Override
    @Nullable
    public String getDefaultMessage() 

Source Link

Usage

From source file:org.exoplatform.acceptance.rest.JsonErrorHandler.java

/**
 * Catch MethodArgumentNotValidException when a Bean Validation error occurs.
 *
 * @param ex The exception trapped//w  w w .  ja v  a2s.c o  m
 * @return A standardized {@link org.exoplatform.acceptance.rest.JsonErrorResponse}
 * @throws java.io.IOException if any.
 */
@ExceptionHandler(MethodArgumentNotValidException.class)
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public JsonErrorResponse processValidationError(MethodArgumentNotValidException ex) throws IOException {
    LOGGER.warn("Validation error : {}", ex.getMessage());
    List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
    List<ObjectError> globalErrors = ex.getBindingResult().getGlobalErrors();
    JsonErrorResponse errors = new JsonErrorResponse();
    for (FieldError fieldError : fieldErrors) {
        errors.addFieldError(fieldError.getField(), fieldError.getDefaultMessage());
    }
    for (ObjectError globalError : globalErrors) {
        errors.addGlobalError(globalError.getObjectName(), globalError.getDefaultMessage());
    }
    return errors;
}

From source file:com.mycompany.capstone.validation.RestValidationHandler.java

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)// w  ww .  j av  a2s. c  o  m
@ResponseBody
public ValidationErrorContainer processValidationErrors(MethodArgumentNotValidException ex) {

    BindingResult bindResult = ex.getBindingResult();
    List<FieldError> fieldErrors = bindResult.getFieldErrors();
    ValidationErrorContainer container = new ValidationErrorContainer();

    for (FieldError error : fieldErrors) {
        ValidationError valError = new ValidationError();

        valError.setFieldName(error.getField());
        valError.setMessage(error.getDefaultMessage());

        container.addError(valError);
    }

    return container;
}

From source file:org.mifos.core.AbstractDtoValidationTest.java

protected void verifyFieldError(Object dto, String fieldName, String errorMessage) {
    Errors errors = getErrors(dto);//from  w ww . jav  a2 s.  c o m
    Assert.assertTrue(errors.getErrorCount() > 0, "Expected errors but got none.");
    FieldError fieldError = errors.getFieldError(fieldName);
    Assert.assertNotNull(fieldError, "Expected error on field " + fieldName + ", but got none");
    Assert.assertEquals(fieldError.getDefaultMessage(), errorMessage, "Incorrect validation error message.");
}

From source file:com.mycompany.addressbookmvc.validation.RestValidationHandler.java

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)/*from w w w.ja  v  a  2  s  . c  o  m*/
@ResponseBody
public ValidationErrorContainer processValidationErrors(MethodArgumentNotValidException ex) {

    BindingResult result = ex.getBindingResult();

    List<FieldError> fieldErrors = result.getFieldErrors();

    ValidationErrorContainer container = new ValidationErrorContainer();

    for (FieldError error : fieldErrors) {

        ValidationError valError = new ValidationError();
        valError.setFieldName(error.getField());
        valError.setMessage(error.getDefaultMessage());

        container.AddError(valError);

    }

    return container;

}

From source file:com.rockagen.gnext.controller.ApplicationController.java

/**
 * Handle errors/*  w ww  .j a va  2  s.c  o  m*/
 *
 * @param errors
 * @return
 */
public ErrorMsg error(Errors errors) {
    FieldError e = errors.getFieldError();
    ErrorMsg em = new ErrorMsg();
    em.field = e.getField();
    em.message = e.getDefaultMessage();
    em.value = e.getRejectedValue();
    return em;

}

From source file:com.google.ie.common.validation.AuditValidator.java

@Override
public void validate(Object target, Errors errors) {

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, IdeaExchangeConstants.USER_KEY,
            IdeaExchangeErrorCodes.FIELD_REQUIRED, IdeaExchangeConstants.Messages.REQUIRED_FIELD);
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, IdeaExchangeConstants.ENTITY_KEY,
            IdeaExchangeErrorCodes.FIELD_REQUIRED, IdeaExchangeConstants.Messages.REQUIRED_FIELD);
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, IdeaExchangeConstants.ACTION,
            IdeaExchangeErrorCodes.FIELD_REQUIRED, IdeaExchangeConstants.Messages.REQUIRED_FIELD);
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, IdeaExchangeConstants.ENTITY_TYPE,
            IdeaExchangeErrorCodes.FIELD_REQUIRED, IdeaExchangeConstants.Messages.REQUIRED_FIELD);
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, IdeaExchangeConstants.AUDIT_DATE,
            IdeaExchangeErrorCodes.FIELD_REQUIRED, IdeaExchangeConstants.Messages.REQUIRED_FIELD);

    if (log.isDebugEnabled()) {
        if (errors.hasErrors()) {
            log.debug("Validator found " + errors.getErrorCount() + " errors");
            for (Iterator<FieldError> iterator = errors.getFieldErrors().iterator(); iterator.hasNext();) {
                FieldError fieldError = iterator.next();
                log.debug("Error found in field: " + fieldError.getField() + " Message :"
                        + fieldError.getDefaultMessage());
            }//from  w ww. ja v a 2  s .c  o  m
        } else {
            log.debug("Validator found no errors");
        }

    }
}

From source file:com.fengduo.bee.web.controller.BaseController.java

/**
 * ??/* www .  j a  v  a  2s  .  c o m*/
 * 
 * @param result
 * @return
 */
public Result showErrors(BindingResult result) {
    StringBuffer errorsb = new StringBuffer();
    if (result.hasErrors()) {
        for (FieldError error : result.getFieldErrors()) {
            errorsb.append(error.getField());
            errorsb.append(error.getDefaultMessage());
            errorsb.append("|");
        }
        String errorsr = errorsb.toString().substring(0, errorsb.toString().length() - 1);
        return Result.failed(errorsr.replaceAll("null", StringUtils.EMPTY));
    }
    return Result.success();
}

From source file:com.mitchellbosecke.pebble.spring.extension.function.bindingresult.GetFieldErrorsFunction.java

@Override
public Object execute(Map<String, Object> args) {
    List<String> results = new ArrayList<>();
    String formName = (String) args.get(PARAM_FORM_NAME);
    String field = (String) args.get(PARAM_FIELD_NAME);

    if (field == null) {
        throw new IllegalArgumentException("Field parameter is required in GetFieldErrorsFunction");
    }/*from  w w w . j  a  v  a2  s  . co  m*/

    EvaluationContext context = (EvaluationContext) args.get("_context");
    Locale locale = context.getLocale();
    BindingResult bindingResult = this.getBindingResult(formName, context);

    if (bindingResult != null) {
        for (FieldError error : bindingResult.getFieldErrors(field)) {
            String msg = this.messageSource.getMessage(error.getCode(), error.getArguments(),
                    error.getDefaultMessage(), locale);
            if (msg != null) {
                results.add(msg);
            }
        }
    }
    return results;
}

From source file:org.terasoluna.tourreservation.app.searchtour.SearchTourFormDateValidatorTest.java

/**
 * Date parse Error//from w w  w  .ja  v a  2s. co  m
 */
@Test
public void testValidate02() {
    SearchTourFormDateValidator validator = new SearchTourFormDateValidator();
    SearchTourForm criteria = new SearchTourForm();
    BindingResult result = new DirectFieldBindingResult(criteria, "SearchTourcriteria");
    criteria.setDepDay(31);
    criteria.setDepMonth(2);
    criteria.setDepYear(2000);

    // run
    validator.validate(criteria, result);

    // assert
    assertThat(result.hasErrors(), is(true));

    FieldError error = result.getFieldError("depYear");

    if (error != null) {
        assertThat(error.getCode(), is("IncorrectDate.inputdate"));
        assertThat(error.getDefaultMessage(), is("Incorrect date was entered."));
    } else {
        fail("error");
    }
}

From source file:com.nicodewet.web.SubscribeController.java

@RequestMapping(value = "/subscribeth.json", method = RequestMethod.POST)
public @ResponseBody ValidationResponse processForm(@Valid final Subscription subscription,
        final BindingResult bindingResult, final ModelMap model) {
    logger.info("Validation");
    ValidationResponse res = new ValidationResponse();
    if (!bindingResult.hasErrors()) {
        res.setStatus("SUCCESS");
    } else {//from www .j a  va  2s.c o m
        res.setStatus("FAIL");
        List<FieldError> allErrors = bindingResult.getFieldErrors();
        List<ErrorMessage> errorMesages = new ArrayList<ErrorMessage>();
        for (FieldError objectError : allErrors) {
            errorMesages.add(new ErrorMessage(objectError.getField(),
                    objectError.getField() + "  " + objectError.getDefaultMessage()));
        }
        res.setErrorMessageList(errorMesages);
    }
    return res;
}