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:com.example.todo.api.common.error.RestGlobalExceptionHandler.java

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
        HttpHeaders headers, HttpStatus status, WebRequest request) {
    ApiError apiError = createApiError(request, "E400");
    for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
        apiError.addDetail(createApiError(request, fieldError, fieldError.getField()));
    }//w  w w.jav  a  2s  . c om
    for (ObjectError objectError : ex.getBindingResult().getGlobalErrors()) {
        apiError.addDetail(createApiError(request, objectError, objectError.getObjectName()));
    }
    return handleExceptionInternal(ex, apiError, headers, status, request);
}

From source file:de.knightsoftnet.validators.server.controller.RestErrorHandler.java

private ValidationResultInterface processFieldErrors(final List<FieldError> pfieldErrors) {
    final ValidationResultInterface validationResult = new ValidationResultData();

    for (final FieldError fieldError : pfieldErrors) {
        final ValidationValueInterface validationDto = new ValidationDto();
        validationDto.setPropertyPath(fieldError.getField());
        validationDto.setMessage(fieldError.getDefaultMessage());
        validationResult.getValidationErrorSet().add(validationDto);
    }/*from  w ww . ja v  a2  s  . c  o m*/

    return validationResult;
}

From source file:org.woofenterprise.dogs.web.controllers.DogsController.java

@RequestMapping(value = "/create", method = RequestMethod.POST)
@RolesAllowed("ADMIN")
public String createDog(Model model, @Valid @ModelAttribute("dog") DogDTO dogDTO, BindingResult bindingResult,
        UriComponentsBuilder uriBuilder, RedirectAttributes redirectAttributes) {
    if (bindingResult.hasErrors()) {
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
        }/*from   w  w  w.  ja  v  a  2s .c  o  m*/
        return "dogs/create";
    }
    try {
        dogDTO = facade.createDog(dogDTO);
        Long id = dogDTO.getId();

        redirectAttributes.addFlashAttribute("alert_success", "Dog #" + id + " was created.");
        return "redirect:" + uriBuilder.path("/dogs/view/{id}").buildAndExpand(id).encode().toUriString();
    } catch (Exception e) {
        log.warn("Exception wile creating: " + e.getMessage());
        redirectAttributes.addFlashAttribute("alert_danger", "Dog was not created.");
        return "redirect:/";
    }
}

From source file:org.woofenterprise.dogs.web.controllers.DogsController.java

@RequestMapping(value = "/update", method = RequestMethod.POST)
@RolesAllowed("ADMIN")
public String updateDog(Model model, @Valid @ModelAttribute("dog") DogDTO dogDTO, BindingResult bindingResult,
        UriComponentsBuilder uriBuilder, RedirectAttributes redirectAttributes) {
    if (bindingResult.hasErrors()) {
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
        }/*w w  w . j  a  v  a 2 s  .c  o m*/
        return "/dogs/edit";
    }

    Long id = dogDTO.getId();
    try {
        facade.updateDog(dogDTO);
        redirectAttributes.addFlashAttribute("alert_success", "Dog #" + id + " was updated.");
        return "redirect:" + uriBuilder.path("/dogs/view/{id}").buildAndExpand(id).encode().toUriString();
    } catch (Exception e) {
        log.warn("Exception wile updating: " + e.getMessage());
        redirectAttributes.addFlashAttribute("alert_danger", "Dog #" + id + " was not edited.");
        return "redirect:/";
    }

}

From source file:cz.muni.fi.pa165.mvc.controllers.TeamController.java

@RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(@Valid @ModelAttribute("teamCreate") TeamDTO formBean, BindingResult bindingResult,
        Model model, RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder) {
    Long id = null;//w ww. j  a v a 2s  . co m
    log.debug("create(teamCreate={})", formBean);
    if (bindingResult.hasErrors()) {
        for (ObjectError ge : bindingResult.getGlobalErrors()) {
            log.trace("ObjectError: {}", ge);
        }
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }
        return "team/new";
    }
    try {
        id = teamFacade.createTeam(formBean);
        redirectAttributes.addFlashAttribute("alert_success",
                "Team: " + teamFacade.getTeamById(id) + " was created");
    } catch (Exception ex) {
        log.warn("cannot Create a team {}");
        redirectAttributes.addFlashAttribute("alert_danger",
                "This team cannot be created because it has already exited in La Liga now.");
    }
    return "redirect:" + uriBuilder.path("/team/list").buildAndExpand(id).encode().toUriString();
}

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

@Override
public void validate(Object target, Errors errors) {
    ProjectDetail projectDetail = (ProjectDetail) target;
    if (StringUtils.isBlank(projectDetail.getProject().getName())) {
        errors.rejectValue(NAME, IdeaExchangeErrorCodes.FIELD_REQUIRED,
                IdeaExchangeConstants.Messages.REQUIRED_FIELD);
        log.warn("Validation Error : " + NAME + " -: " + IdeaExchangeConstants.Messages.REQUIRED_FIELD);
    }/*  w w w .ja  v  a2s  .c om*/
    if (!StringUtils.isBlank(projectDetail.getProject().getName())
            && projectDetail.getProject().getName().trim().length() > LENGTH_500) {
        errors.rejectValue(NAME, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT,
                IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
        log.warn("Validation Error : " + NAME + " -: "
                + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
    }
    if (!StringUtils.isBlank(projectDetail.getProject().getDescription())
            && projectDetail.getProject().getDescription().trim().length() > LENGTH_3000) {
        errors.rejectValue(DESCRIPTION, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT,
                IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
        log.warn("Validation Error : " + DESCRIPTION + " -: "
                + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
    }
    List<Developer> developers = projectDetail.getDevelopers();
    if (developers != null) {
        for (Developer developer : developers) {
            if (!StringUtils.isBlank(developer.getName()) && developer.getName().trim().length() > LENGTH_50) {
                errors.rejectValue(DEVELOPER_NAME, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT,
                        IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
                log.warn("Validation Error : " + DEVELOPER_NAME + " -: "
                        + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
            }
            if (!StringUtils.isBlank(developer.getEmailId())
                    && developer.getEmailId().trim().length() > LENGTH_50) {
                errors.reject(IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT,
                        DEVELOPER_EMAIL + ":" + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
                log.warn("Validation Error : " + DEVELOPER_EMAIL + " -: "
                        + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
            }
        }
    }

    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());
            }
        } else {
            log.debug("Validator found no errors");
        }

    }
}

From source file:cz.muni.fi.pa165.mvc.controllers.TeamController.java

@RequestMapping(value = "/edit", method = RequestMethod.POST)
public String edit(@Valid @ModelAttribute("teamEdit") TeamDTO formBean, BindingResult bindingResult,
        Model model, RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder) {
    log.debug("edit(teamEdit={})", formBean);
    if (bindingResult.hasErrors()) {
        log.debug("some errror");
        for (ObjectError ge : bindingResult.getGlobalErrors()) {
            log.trace("ObjectError: {}", ge);

        }//ww w.  ja  v a  2s.co  m
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }
        return "team/edit";

    }
    try {
        teamFacade.updateTeam(formBean);
        redirectAttributes.addFlashAttribute("alert_success", "Team was edited");
    } catch (Exception ex) {
        log.warn("cannot edit this team {}");
        redirectAttributes.addFlashAttribute("alert_danger",
                "Team's name has already exited or any errors happen, please check again!");
    }
    return "redirect:" + uriBuilder.path("/team/list").toUriString();

}

From source file:org.jasig.portlet.blackboardvcportlet.mvc.sessionmngr.ManageMediaFilesController.java

protected Map<String, String> getFieldErrors(BindingResult bindingResult) {
    final Map<String, String> fieldErrors = new LinkedHashMap<String, String>();
    for (FieldError error : bindingResult.getFieldErrors()) {
        fieldErrors.put(error.getField(), error.getDefaultMessage());
    }// w  ww  .  j a  va2s  .  c om
    return fieldErrors;
}

From source file:by.creepid.docgeneration.validation.RegValidator.java

@Override
public void validate(FacesContext context, UIComponent component, Object value) {

    Locale locale = FacesContext.getCurrentInstance().getExternalContext().getRequestLocale();

    WebUtils.clearFacesMessages(context);
    FirmReg firmReg = (FirmReg) WebUtils.findBean("reg");

    System.out.println(firmReg.toString());

    Errors errors = new BeanPropertyBindingResult(firmReg, "reg");
    firmRegValidator.validate(firmReg, errors);

    if (errors != null && errors.hasErrors()) {
        String message = messageSource.getMessage("error.validation", null, locale);

        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null));

        List<FieldError> fieldErrors = errors.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            message = messageSource.getMessage(fieldError, locale);
            System.out.println(/* ww w.jav  a2  s  .  c  o m*/
                    fieldError.getField() + "   " + fieldError.getCode() + " " + fieldError.getObjectName());

            context.addMessage(fieldError.getField(),
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, message, message));
        }
    }
}