Search in sources :

Example 81 with FieldError

use of org.springframework.validation.FieldError in project BroadleafCommerce by BroadleafCommerce.

the class AdminAbstractController method populateJsonValidationErrors.

/**
 * Populates the given <b>json</b> response object based on the given <b>form</b> and <b>result</b>
 * @return the same <b>result</b> that was passed in
 */
protected JsonResponse populateJsonValidationErrors(EntityForm form, BindingResult result, JsonResponse json) {
    List<Map<String, Object>> errors = new ArrayList<>();
    for (FieldError e : result.getFieldErrors()) {
        Map<String, Object> errorMap = new HashMap<>();
        errorMap.put("errorType", "field");
        String fieldName = e.getField().substring(e.getField().indexOf("[") + 1, e.getField().indexOf("]")).replace("_", "-");
        errorMap.put("field", fieldName);
        errorMap.put("message", translateErrorMessage(e));
        errorMap.put("code", e.getCode());
        String tabFieldName = fieldName.replaceAll("-+", ".");
        Tab errorTab = form.findTabForField(tabFieldName);
        if (errorTab != null) {
            errorMap.put("tab", errorTab.getTitle());
        }
        errors.add(errorMap);
    }
    for (ObjectError e : result.getGlobalErrors()) {
        Map<String, Object> errorMap = new HashMap<>();
        errorMap.put("errorType", "global");
        errorMap.put("code", e.getCode());
        errorMap.put("message", translateErrorMessage(e));
        errors.add(errorMap);
    }
    json.with("errors", errors);
    return json;
}
Also used : ObjectError(org.springframework.validation.ObjectError) Tab(org.broadleafcommerce.openadmin.web.form.entity.Tab) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) FieldError(org.springframework.validation.FieldError) HashMap(java.util.HashMap) Map(java.util.Map) MultiValueMap(org.springframework.util.MultiValueMap)

Example 82 with FieldError

use of org.springframework.validation.FieldError in project BroadleafCommerce by BroadleafCommerce.

the class AdminTranslationController method resultToJS.

/**
 * analyzes the error information, and converts it into a Javascript object  string, which can be passed to to the HTML form through the entityForm
 * @param result
 * @return
 */
private String resultToJS(BindingResult result) {
    StringBuffer sb = new StringBuffer("[");
    List<ObjectError> errors = result.getAllErrors();
    for (ObjectError objectError : errors) {
        if (objectError instanceof FieldError) {
            FieldError ferr = (FieldError) objectError;
            sb.append("{");
            String fieldOnly = StringUtil.extractFieldNameFromExpression(ferr.getField());
            sb.append("\"").append(fieldOnly).append("\":");
            String localizedMessage = BLCMessageUtils.getMessage(ferr.getDefaultMessage());
            sb.append("\"").append(localizedMessage).append("\"");
            sb.append("},");
        }
    }
    if (sb.length() > 1) {
        // the last comma
        sb.deleteCharAt(sb.length() - 1);
    }
    sb.append("]");
    return sb.toString();
}
Also used : ObjectError(org.springframework.validation.ObjectError) FieldError(org.springframework.validation.FieldError)

Example 83 with FieldError

use of org.springframework.validation.FieldError in project google-app-engine-jappstart by taylorleese.

the class RegisterController method submit.

/**
 * Handle the create account form submission.
 *
 * @param register the register form bean
 * @param binding the binding result
 * @param request the HTTP servlet request
 * @return the path
 */
@RequestMapping(value = "/create", method = RequestMethod.POST)
public final String submit(@ModelAttribute(REGISTER) @Valid final Register register, final BindingResult binding, final HttpServletRequest request) {
    final Locale locale = localeResolver.resolveLocale(request);
    if (binding.hasErrors()) {
        return "create";
    }
    final UserAccount user = new UserAccount(register.getUsername());
    user.setDisplayName(register.getDisplayName());
    user.setEmail(register.getEmail());
    user.setPassword(passwordEncoder.encodePassword(register.getPassword(), user.getSalt()));
    try {
        userDetailsService.addUser(user, locale);
    } catch (DuplicateUserException e) {
        binding.addError(new FieldError(REGISTER, "username", messageSource.getMessage("create.error.username", null, locale)));
        return "create";
    }
    return "redirect:/register/success";
}
Also used : Locale(java.util.Locale) FieldError(org.springframework.validation.FieldError) UserAccount(com.jappstart.model.auth.UserAccount) DuplicateUserException(com.jappstart.exception.DuplicateUserException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 84 with FieldError

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

the class ValidatorFactoryTests method testSpringValidationWithErrorInSetElement.

@Test
public void testSpringValidationWithErrorInSetElement() {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.afterPropertiesSet();
    ValidPerson person = new ValidPerson();
    person.getAddressSet().add(new ValidAddress());
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
    validator.validate(person, result);
    assertThat(result.getErrorCount()).isEqualTo(3);
    FieldError fieldError = result.getFieldError("name");
    assertThat(fieldError.getField()).isEqualTo("name");
    fieldError = result.getFieldError("address.street");
    assertThat(fieldError.getField()).isEqualTo("address.street");
    fieldError = result.getFieldError("addressSet[].street");
    assertThat(fieldError.getField()).isEqualTo("addressSet[].street");
}
Also used : BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) FieldError(org.springframework.validation.FieldError) Test(org.junit.jupiter.api.Test)

Example 85 with FieldError

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

the class SpringValidatorAdapterTests method testApplyMessageSourceResolvableToStringArgumentValueWithAlwaysUseMessageFormat.

// SPR-15123
@Test
public void testApplyMessageSourceResolvableToStringArgumentValueWithAlwaysUseMessageFormat() {
    messageSource.setAlwaysUseMessageFormat(true);
    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)

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