Search in sources :

Example 86 with FieldError

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

the class SpringValidatorAdapterTests method testApplyMessageSourceResolvableToStringArgumentValueWithUnresolvedLogicalFieldName.

// SPR-13406
@Test
public void testApplyMessageSourceResolvableToStringArgumentValueWithUnresolvedLogicalFieldName() {
    TestBean testBean = new TestBean();
    testBean.setEmail("test@example.com");
    testBean.setConfirmEmail("TEST@EXAMPLE.IO");
    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean");
    validatorAdapter.validate(testBean, errors);
    assertThat(errors.getFieldErrorCount("email")).isEqualTo(1);
    assertThat(errors.getFieldValue("email")).isEqualTo("test@example.com");
    assertThat(errors.getFieldErrorCount("confirmEmail")).isEqualTo(1);
    FieldError error1 = errors.getFieldError("email");
    FieldError error2 = errors.getFieldError("confirmEmail");
    assertThat(error1).isNotNull();
    assertThat(error2).isNotNull();
    assertThat(messageSource.getMessage(error1, Locale.ENGLISH)).isEqualTo("email must be same value as confirmEmail");
    assertThat(messageSource.getMessage(error2, Locale.ENGLISH)).isEqualTo("Email required");
    assertThat(error1.contains(ConstraintViolation.class)).isTrue();
    assertThat(error1.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("email");
    assertThat(error2.contains(ConstraintViolation.class)).isTrue();
    assertThat(error2.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("confirmEmail");
}
Also used : BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) FieldError(org.springframework.validation.FieldError) Test(org.junit.jupiter.api.Test)

Example 87 with FieldError

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

the class SpringValidatorAdapterTests method testPatternMessage.

@Test
public void testPatternMessage() {
    TestBean testBean = new TestBean();
    testBean.setEmail("X");
    testBean.setConfirmEmail("X");
    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean");
    validatorAdapter.validate(testBean, errors);
    assertThat(errors.getFieldErrorCount("email")).isEqualTo(1);
    assertThat(errors.getFieldValue("email")).isEqualTo("X");
    FieldError error = errors.getFieldError("email");
    assertThat(error).isNotNull();
    assertThat(messageSource.getMessage(error, Locale.ENGLISH)).contains("[\\w.'-]{1,}@[\\w.'-]{1,}");
    assertThat(error.contains(ConstraintViolation.class)).isTrue();
    assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("email");
}
Also used : BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) FieldError(org.springframework.validation.FieldError) Test(org.junit.jupiter.api.Test)

Example 88 with FieldError

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

the class BaseController method buildFieldError.

/**
 * 错误:参数错误
 *
 * @param bindingResult
 *
 * @return
 */
protected JsonObjectBase buildFieldError(BindingResult bindingResult, ErrorCode errorCode) {
    Map<String, String> errors = new HashMap<String, String>();
    for (Object object : bindingResult.getAllErrors()) {
        if (object instanceof FieldError) {
            FieldError fieldError = (FieldError) object;
            String message = fieldError.getDefaultMessage();
            errors.put(fieldError.getField(), message);
        }
    }
    if (errorCode == null) {
        return JsonObjectUtils.buildFieldError(errors, ErrorCode.FIELD_ERROR);
    }
    return JsonObjectUtils.buildFieldError(errors, errorCode);
}
Also used : HashMap(java.util.HashMap) FieldError(org.springframework.validation.FieldError)

Example 89 with FieldError

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

the class DataBindingUtils method bindObjectToDomainInstance.

/**
 * Binds the given source object to the given target object performing type conversion if necessary
 *
 * @param entity The PersistentEntity instance
 * @param object The object to bind to
 * @param source The source object
 * @param include The list of properties to include
 * @param exclude The list of properties to exclude
 * @param filter The prefix to filter by
 *
 * @see org.grails.datastore.mapping.model.PersistentEntity
 *
 * @return A BindingResult if there were errors or null if it was successful
 */
@SuppressWarnings("unchecked")
public static BindingResult bindObjectToDomainInstance(PersistentEntity entity, Object object, Object source, List include, List exclude, String filter) {
    BindingResult bindingResult = null;
    GrailsApplication grailsApplication = Holders.findApplication();
    try {
        final DataBindingSource bindingSource = createDataBindingSource(grailsApplication, object.getClass(), source);
        final DataBinder grailsWebDataBinder = getGrailsWebDataBinder(grailsApplication);
        grailsWebDataBinder.bind(object, bindingSource, filter, include, exclude);
    } catch (InvalidRequestBodyException e) {
        String messageCode = "invalidRequestBody";
        Class objectType = object.getClass();
        String defaultMessage = "An error occurred parsing the body of the request";
        String[] codes = getMessageCodes(messageCode, objectType);
        bindingResult = new BeanPropertyBindingResult(object, objectType.getName());
        bindingResult.addError(new ObjectError(bindingResult.getObjectName(), codes, null, defaultMessage));
    } catch (Exception e) {
        bindingResult = new BeanPropertyBindingResult(object, object.getClass().getName());
        bindingResult.addError(new ObjectError(bindingResult.getObjectName(), e.getMessage()));
    }
    if (entity != null && bindingResult != null) {
        BindingResult newResult = new ValidationErrors(object);
        for (Object error : bindingResult.getAllErrors()) {
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                final boolean isBlank = BLANK.equals(fieldError.getRejectedValue());
                if (!isBlank) {
                    newResult.addError(fieldError);
                } else {
                    PersistentProperty property = entity.getPropertyByName(fieldError.getField());
                    if (property != null) {
                        final boolean isOptional = property.isNullable();
                        if (!isOptional) {
                            newResult.addError(fieldError);
                        }
                    } else {
                        newResult.addError(fieldError);
                    }
                }
            } else {
                newResult.addError((ObjectError) error);
            }
        }
        bindingResult = newResult;
    }
    MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(object.getClass());
    if (mc.hasProperty(object, "errors") != null && bindingResult != null) {
        ValidationErrors errors = new ValidationErrors(object);
        errors.addAllErrors(bindingResult);
        mc.setProperty(object, "errors", errors);
    }
    return bindingResult;
}
Also used : BindingResult(org.springframework.validation.BindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) ValidationErrors(grails.validation.ValidationErrors) FieldError(org.springframework.validation.FieldError) CollectionDataBindingSource(grails.databinding.CollectionDataBindingSource) DataBindingSource(grails.databinding.DataBindingSource) PersistentProperty(org.grails.datastore.mapping.model.PersistentProperty) InvalidRequestBodyException(org.grails.web.databinding.bindingsource.InvalidRequestBodyException) GrailsConfigurationException(org.grails.core.exceptions.GrailsConfigurationException) ObjectError(org.springframework.validation.ObjectError) MetaClass(groovy.lang.MetaClass) GrailsApplication(grails.core.GrailsApplication) InvalidRequestBodyException(org.grails.web.databinding.bindingsource.InvalidRequestBodyException) GrailsDomainClass(grails.core.GrailsDomainClass) MetaClass(groovy.lang.MetaClass) DataBinder(grails.databinding.DataBinder)

Example 90 with FieldError

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

the class OriginTrackedFieldErrorTests method ofShouldReturnOriginCapableFieldError.

@Test
void ofShouldReturnOriginCapableFieldError() {
    FieldError fieldError = OriginTrackedFieldError.of(FIELD_ERROR, ORIGIN);
    assertThat(fieldError.getObjectName()).isEqualTo("foo");
    assertThat(fieldError.getField()).isEqualTo("bar");
    assertThat(Origin.from(fieldError)).isEqualTo(ORIGIN);
}
Also used : FieldError(org.springframework.validation.FieldError) Test(org.junit.jupiter.api.Test)

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