Search in sources :

Example 31 with FieldError

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

the class ValidationBindHandlerTests method validationShouldBeSkippedIfPreviousValidationErrorPresent.

@Test
void validationShouldBeSkippedIfPreviousValidationErrorPresent() {
    this.sources.add(new MockConfigurationPropertySource("foo.inner.person-age", 2));
    BindValidationException cause = bindAndExpectValidationError(() -> this.binder.bind(ConfigurationPropertyName.of("foo"), Bindable.of(ExampleCamelCase.class), this.handler));
    FieldError fieldError = (FieldError) cause.getValidationErrors().getAllErrors().get(0);
    assertThat(fieldError.getField()).isEqualTo("personAge");
}
Also used : MockConfigurationPropertySource(org.springframework.boot.context.properties.source.MockConfigurationPropertySource) FieldError(org.springframework.validation.FieldError) Test(org.junit.jupiter.api.Test)

Example 32 with FieldError

use of org.springframework.validation.FieldError in project disconf by knightliao.

the class ParamValidateUtils method getParamErrors.

/**
 * 从bindException中获取到参数错误类型,参数错误
 */
public static ModelAndView getParamErrors(BindException be) {
    // 构造error的映射
    Map<String, String> paramErrors = new HashMap<String, String>();
    Map<String, Object[]> paramArgusErrors = new HashMap<String, Object[]>();
    for (Object error : be.getAllErrors()) {
        if (error instanceof FieldError) {
            FieldError fe = (FieldError) error;
            String field = fe.getField();
            // 默认的message
            String message = fe.getDefaultMessage();
            try {
                contextReader.getMessage(message, fe.getArguments());
            } catch (NoSuchMessageException e) {
                // 如果有code,则从前往后遍历Code(特殊到一般),修改message为code所对应
                for (int i = fe.getCodes().length - 1; i >= 0; i--) {
                    try {
                        String code = fe.getCodes()[i];
                        String info = contextReader.getMessage(code, fe.getArguments());
                        LOG.debug(code + "\t" + info);
                        message = code;
                    } catch (NoSuchMessageException e2) {
                        LOG.debug("");
                    }
                }
            }
            // 最终的消息
            paramErrors.put(field, message);
            paramArgusErrors.put(field, fe.getArguments());
        }
    }
    return ParamValidateUtils.paramError(paramErrors, paramArgusErrors, ErrorCode.FIELD_ERROR);
}
Also used : NoSuchMessageException(org.springframework.context.NoSuchMessageException) HashMap(java.util.HashMap) FieldError(org.springframework.validation.FieldError)

Example 33 with FieldError

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

the class DateTimeFormattingTests method isoLocalDateWithInvalidFormat.

@Test
void isoLocalDateWithInvalidFormat() {
    MutablePropertyValues propertyValues = new MutablePropertyValues();
    String propertyName = "isoLocalDate";
    propertyValues.add(propertyName, "2009-31-10");
    binder.bind(propertyValues);
    BindingResult bindingResult = binder.getBindingResult();
    assertThat(bindingResult.getErrorCount()).isEqualTo(1);
    FieldError fieldError = bindingResult.getFieldError(propertyName);
    assertThat(fieldError.unwrap(TypeMismatchException.class)).hasMessageContaining("for property 'isoLocalDate'").hasCauseInstanceOf(ConversionFailedException.class).getCause().hasMessageContaining("for value '2009-31-10'").hasCauseInstanceOf(IllegalArgumentException.class).getCause().hasMessageContaining("Parse attempt failed for value [2009-31-10]").hasCauseInstanceOf(DateTimeParseException.class).getCause().hasMessageContainingAll("Unable to parse date time value \"2009-31-10\" using configuration from", "@org.springframework.format.annotation.DateTimeFormat", "iso=DATE").hasCauseInstanceOf(DateTimeParseException.class).getCause().hasMessageStartingWith("Text '2009-31-10'").hasCauseInstanceOf(DateTimeException.class).getCause().hasMessageContaining("Invalid value for MonthOfYear (valid values 1 - 12): 31").hasNoCause();
}
Also used : DateTimeParseException(java.time.format.DateTimeParseException) BindingResult(org.springframework.validation.BindingResult) DateTimeException(java.time.DateTimeException) ConversionFailedException(org.springframework.core.convert.ConversionFailedException) MutablePropertyValues(org.springframework.beans.MutablePropertyValues) FieldError(org.springframework.validation.FieldError) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 34 with FieldError

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

the class DateFormattingTests method styleDateWithInvalidFormat.

@Test
void styleDateWithInvalidFormat() {
    String propertyName = "styleDate";
    String propertyValue = "99/01/01";
    MutablePropertyValues propertyValues = new MutablePropertyValues();
    propertyValues.add(propertyName, propertyValue);
    binder.bind(propertyValues);
    BindingResult bindingResult = binder.getBindingResult();
    assertThat(bindingResult.getErrorCount()).isEqualTo(1);
    FieldError fieldError = bindingResult.getFieldError(propertyName);
    TypeMismatchException exception = fieldError.unwrap(TypeMismatchException.class);
    assertThat(exception).hasMessageContaining("for property 'styleDate'").hasCauseInstanceOf(ConversionFailedException.class).getCause().hasMessageContaining("for value '99/01/01'").hasCauseInstanceOf(IllegalArgumentException.class).getCause().hasMessageContaining("Parse attempt failed for value [99/01/01]").hasCauseInstanceOf(ParseException.class).getCause().hasMessageContainingAll("Unable to parse date time value \"99/01/01\" using configuration from", "@org.springframework.format.annotation.DateTimeFormat", "style=", "S-", "iso=NONE").hasCauseInstanceOf(ParseException.class).getCause().hasMessageStartingWith("Unparseable date: \"99/01/01\"").hasNoCause();
}
Also used : BindingResult(org.springframework.validation.BindingResult) MutablePropertyValues(org.springframework.beans.MutablePropertyValues) TypeMismatchException(org.springframework.beans.TypeMismatchException) FieldError(org.springframework.validation.FieldError) ParseException(java.text.ParseException) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 35 with FieldError

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

the class SpringValidatorAdapterTests method testApplyMessageSourceResolvableToStringArgumentValueWithResolvedLogicalFieldName.

// SPR-13406
@Test
public void testApplyMessageSourceResolvableToStringArgumentValueWithResolvedLogicalFieldName() throws Exception {
    TestBean testBean = new TestBean();
    testBean.setPassword("password");
    testBean.setConfirmPassword("PASSWORD");
    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean");
    validatorAdapter.validate(testBean, errors);
    assertThat(errors.getFieldErrorCount("password")).isEqualTo(1);
    assertThat(errors.getFieldValue("password")).isEqualTo("password");
    FieldError error = errors.getFieldError("password");
    assertThat(error).isNotNull();
    assertThat(messageSource.getMessage(error, Locale.ENGLISH)).isEqualTo("Password must be same value as Password(Confirm)");
    assertThat(error.contains(ConstraintViolation.class)).isTrue();
    assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("password");
    assertThat(SerializationTestUtils.serializeAndDeserialize(error.toString())).isEqualTo(error.toString());
}
Also used : BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) FieldError(org.springframework.validation.FieldError) Test(org.junit.jupiter.api.Test)

Aggregations

FieldError (org.springframework.validation.FieldError)101 Test (org.junit.jupiter.api.Test)24 ObjectError (org.springframework.validation.ObjectError)20 BindingResult (org.springframework.validation.BindingResult)19 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)17 ApiOperation (io.swagger.annotations.ApiOperation)13 BeanPropertyBindingResult (org.springframework.validation.BeanPropertyBindingResult)12 Errors (org.springframework.validation.Errors)11 ArrayList (java.util.ArrayList)10 BindException (org.springframework.validation.BindException)7 Locale (java.util.Locale)6 CustomResult (com.megagao.production.ssm.domain.customize.CustomResult)5 Test (org.junit.Test)5 MapBindingResult (org.springframework.validation.MapBindingResult)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 Method (java.lang.reflect.Method)4 HashMap (java.util.HashMap)4 ErrorMessage (org.springframework.cloud.servicebroker.model.error.ErrorMessage)4