Example usage for org.springframework.validation FieldError getField

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

Introduction

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

Prototype

public String getField() 

Source Link

Document

Return the affected field of the object.

Usage

From source file:cz.muni.fi.editor.webapp.controllers.ajax.AjaxUserController.java

@RequestMapping(value = "/", method = RequestMethod.POST)
public @ResponseBody ValidationResponse processUpdateuser(Model model,
        @RequestBody @Valid UserFormProfile userFormProfile, BindingResult bindingResult) {
    ValidationResponse response = new ValidationResponse();
    if (bindingResult.hasErrors()) {
        response.setStatus("FAIL");

        List<ErrorMessage> messages = new ArrayList<>();

        for (FieldError error : bindingResult.getFieldErrors()) {
            ErrorMessage em = new ErrorMessage();
            em.setField(error.getField());
            em.setMessage(error.getDefaultMessage());

            messages.add(em);/*from   w w  w . j a  v a  2 s  .c  om*/
        }

        response.setMessages(messages);
    } else {
        try {
            userService.update(mapper.map(userFormProfile, UserDTO.class));
            response.setStatus("SUCCESS");
        } catch (FieldException ex) {
            log.warn(ex);
            response.setStatus("FAIL");
        }

    }

    return response;
}

From source file:com.oak_yoga_studio.controller.ProductController.java

@RequestMapping(value = "/productEdit", method = RequestMethod.POST)
public String updateProduct(@Valid Product product, BindingResult result,
        @RequestParam("file") MultipartFile file) {

    if (!result.hasErrors()) {
        try {//from w w  w  .  j a v  a  2  s .co m
            product.setImage(file.getBytes());
            product.setStatus("ACTIVE");
            productService.updateProduct(product);
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        return "redirect:/products";
    } else {
        for (FieldError err : result.getFieldErrors()) {
            System.out.println(err.getField() + ": " + err.getDefaultMessage());

        }
        return "editProduct";
    }

}

From source file:org.jtalks.common.web.dto.ValidationResults.java

/**
 * This method populates field errors from the specified {@link BindingResult} to the {@code fieldErrors} structure
 *
 * @param bindingResult Binding result to populate field errors from
 *///from   www  .  ja  va2  s . c  o  m
private void populateFieldErrors(BindingResult bindingResult) {
    fieldErrors = new HashMap<String, List<String>>();
    for (FieldError error : bindingResult.getFieldErrors()) {
        List<String> currentFieldErrors = fieldErrors.get(error.getField());
        if (currentFieldErrors == null) {
            currentFieldErrors = new ArrayList<String>();
        }

        currentFieldErrors.add(error.getDefaultMessage());
        fieldErrors.put(error.getField(), currentFieldErrors);
    }
}

From source file:com.tapas.evidence.fe.form.EvidenceForm.java

public boolean validate(final MetaModel metaModel, final Validator validator, final Model model,
        final IUiMessageSource messageSource, final Locale locale) {
    boolean result = false;
    final BindingResult validationResult = new BeanPropertyBindingResult(model, model.getClass().getName());
    clearFields(metaModel);/* w  w w .j ava2  s  . c o  m*/
    validator.validate(model, validationResult);
    if (validationResult.hasErrors()) {
        for (FieldError error : validationResult.getFieldErrors()) {
            final String field = error.getField();
            final String message = getMessage(error.getCodes(), messageSource, locale);
            final Field fieldComponent = this.getField(field);
            if (fieldComponent instanceof AbstractField) {
                ((AbstractField) fieldComponent).setComponentError(new UserError(message));
            }
        }
        result = false;
    } else {
        result = true;
    }
    return result;
}

From source file:org.frat.common.exception.BindingResultExceptionHandler.java

/**
 * // w w w .  j  ava 2 s  .  co m
 * Description: set the result dto.
 * 
 * @param locale
 * 
 * @param constraintViolation
 * @throws NoSuchFieldException
 */
private void setResultDto(BindingResult bindingResult, List<ValidationResultDto> errorData, String formId,
        boolean notManually) {
    List<FieldError> fieldErros = bindingResult.getFieldErrors();
    String beanName = bindingResult.getObjectName();
    Object rootObject = bindingResult.getTarget();
    Class<?> rootClass = rootObject.getClass();
    if (fieldErros != null && fieldErros.size() > 0) {
        for (FieldError fieldError : fieldErros) {
            final String fieldName = fieldError.getField();
            String message = fieldError.getDefaultMessage();
            final String errorCode = fieldError.getCode();
            if (StringUtils.isEmpty(message)) {
                message = MessageUtil.getMessage(StringUtils.isNotEmpty(errorCode) ? errorCode : message);
            }
            setFieldErrorMap(fieldName, beanName, rootClass, errorData, message, formId, notManually);
        }
    }
}

From source file:com.simplecrud.controller.RegistrationController.java

/**
 * Process Registration Data//from   w w w  . ja v  a2s. com
 *
 * @param member
 * @param result
 * @param model
 * @param request
 * @return view
 */
@RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView validateUser(@Valid @ModelAttribute("newMemberForm") ValidateMember member,
        BindingResult result, Model model, HttpServletRequest request) {

    FormStatus sFormStatus = new FormStatus();

    //if validated form has errors
    if (result.hasErrors()) {

        //handle errors in the inputs
        List<FieldError> errors = result.getFieldErrors();
        for (FieldError error : errors) {
            System.out.println(error.getField() + " - " + error.getDefaultMessage());

            if ("username".equals(error.getField())) {
                //set error message in username input
                sFormStatus.setsUsername(error.getDefaultMessage());

            }

            if ("password".equals(error.getField())) {
                //set error message in password input
                sFormStatus.setsPassword(error.getDefaultMessage());
            }

            if ("email".equals(error.getField())) {
                //set error message in email input
                sFormStatus.setsEmail(error.getDefaultMessage());
            }

        }
        System.out.println(result.getFieldErrors());
        return new ModelAndView("redirect:/registration.html?" + "&ErrorUsername=" + sFormStatus.getsUsername()
                + "" + "&ErrorPassword=" + sFormStatus.getsPassword() + "" + "&ErrorEmail="
                + sFormStatus.getsEmail() + "" + "&response=error");

    } else {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");

        //try to save the form
        try {
            newMemberDao.persist(new NewMember(username, password, email));
            System.out.println(result + "Form Results - Valid and Saved");

            return new ModelAndView("redirect:/registration.html?response=success");

        } catch (Exception e) {
            System.out.println(e.getMessage() + "  User Already Exist");
        }
        return new ModelAndView("redirect:/registration.html?response=UserAlreadyExist");
    }

}

From source file:com.logsniffer.web.controller.exception.RestErrorHandler.java

private ErrorResponse processFieldErrors(final ErrorResponse er, final List<FieldError> fieldErrors) {
    final Map<String, String> errors = new HashMap<String, String>();
    for (final FieldError fieldError : fieldErrors) {
        final String localizedErrorMessage = resolveLocalizedErrorMessage(fieldError);
        errors.put(fieldError.getField(), localizedErrorMessage);
    }/*from  ww  w . j  a va 2s.c o  m*/
    er.setBindErrors(errors);
    return er;
}

From source file:net.jkratz.igdb.controller.advice.ErrorController.java

private Map<String, Object> convertConstraintViolation(MethodArgumentNotValidException ex) {
    Map<String, Object> result = Maps.newHashMap();
    for (FieldError error : ex.getBindingResult().getFieldErrors()) {
        result.put(error.getField(), error.getDefaultMessage());
    }/*ww  w .  j a va2  s. c  om*/
    return result;
}

From source file:se.skltp.cooperation.web.rest.exception.DefaultExceptionHandler.java

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)//from   w  ww  .ja v a  2 s.  c  o m
@ResponseBody
public ProblemDetail processValidationError(HttpServletRequest request, MethodArgumentNotValidException e) {
    log.debug("Handling form validation error");

    ValidationError error = new ValidationError();
    buildErrorMessage(request, e, HttpStatus.BAD_REQUEST, error);

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

    for (FieldError fieldError : fieldErrors) {
        log.debug("Adding error message: {} to field: {}", fieldError.getDefaultMessage(),
                fieldError.getField());
        error.addFieldError(fieldError.getField(), fieldError.getCode(), fieldError.getDefaultMessage());
    }

    return error;
}

From source file:it.f2informatica.core.validator.utils.ErrorMessageResolver.java

public List<ErrorMessage> resolveErrorCodes(List<FieldError> fieldErrors, final Locale locale) {
    return Lists.newArrayList(Iterables.transform(fieldErrors, new Function<FieldError, ErrorMessage>() {
        @Override//w ww.  j  a  v a2s .  c o  m
        public ErrorMessage apply(FieldError input) {
            String errorCode = input.getCode();
            String errorMessage = messageSource.getMessage(errorCode, input.getArguments(), locale);
            String field = Iterables.getFirst(Arrays.asList(input.getField().split("\\.")), "");
            return new ErrorMessage(field, errorCode, errorMessage);
        }
    }));
}