Example usage for org.springframework.validation BindingResult getFieldErrors

List of usage examples for org.springframework.validation BindingResult getFieldErrors

Introduction

In this page you can find the example usage for org.springframework.validation BindingResult getFieldErrors.

Prototype

List<FieldError> getFieldErrors();

Source Link

Document

Get all errors associated with a field.

Usage

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
 *///w  w  w .ja v a  2  s  .  co 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.github.iexel.fontus.web.rest.GlobalControllerAdviceRest.java

private String[] fetchValidationErrorsAsStringArray(BindingResult bindingResult, Locale locale) {

    String[] errorArray = null;//from ww w.  java  2 s .c o m

    if (bindingResult.hasErrors()) {
        List<FieldError> errors = bindingResult.getFieldErrors();
        errorArray = new String[errors.size() * 2];
        int counter = 0;

        for (FieldError error : errors) {
            errorArray[counter] = error.getField();
            errorArray[counter + 1] = messageSource.getMessage(error, locale);
            counter += 2;
        }
    }
    return errorArray;
}

From source file:com.github.lynxdb.server.api.http.handlers.EpVhost.java

@RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity createVhost(Authentication _authentication, @RequestBody @Valid VhostCreationRequest _vcr,
        BindingResult _bindingResult) {

    if (_bindingResult.hasErrors()) {
        ArrayList<String> errors = new ArrayList();
        _bindingResult.getFieldErrors().forEach((FieldError t) -> {
            errors.add(t.getField() + ": " + t.getDefaultMessage());
        });/*from   w  w  w.j  av  a  2s  .c  om*/
        return new ErrorResponse(mapper, HttpStatus.BAD_REQUEST, errors.toString()).response();
    }

    Vhost v = new Vhost(_vcr);

    vhosts.save(v);

    return ResponseEntity.ok(v);
}

From source file:org.easy.spring.web.ValidationSupport.java

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)/*  w w w. java  2  s  .c om*/
@ResponseBody
public ValidationError processValidationError(MethodArgumentNotValidException ex) {
    BindingResult errors = ex.getBindingResult();
    ValidationError result = new ValidationError(errors.getObjectName(), errors.getNestedPath(),
            errors.getErrorCount(), errors.getFieldErrors());

    return result;//processFieldErrors(fieldErrors);
}

From source file:com.fengduo.bee.web.controller.BaseController.java

/**
 * ??/*from ww w  . j a v  a  2s .co  m*/
 * 
 * @param result
 * @return
 */
public Result showErrors(BindingResult result) {
    StringBuffer errorsb = new StringBuffer();
    if (result.hasErrors()) {
        for (FieldError error : result.getFieldErrors()) {
            errorsb.append(error.getField());
            errorsb.append(error.getDefaultMessage());
            errorsb.append("|");
        }
        String errorsr = errorsb.toString().substring(0, errorsb.toString().length() - 1);
        return Result.failed(errorsr.replaceAll("null", StringUtils.EMPTY));
    }
    return Result.success();
}

From source file:com.sastix.cms.server.utils.ValidationHelper.java

public void validate(BindingResult result) throws ContentValidationException {
    if (result == null) {
        return;/*  w w w .  j a  va 2 s . c om*/
    }
    if (!result.hasErrors()) {
        return;
    }
    String message = createMessage(result.getFieldErrors());
    LOG.trace("Field errors: " + message);
    throw new ContentValidationException(message);
}

From source file:com.github.lynxdb.server.api.http.handlers.EpSuggest.java

@RequestMapping(path = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity post(@RequestBody @Valid SuggestRequest _request, Authentication _authentication,
        BindingResult _bindingResult) {

    if (_bindingResult.hasErrors()) {
        ArrayList<String> errors = new ArrayList();
        _bindingResult.getFieldErrors().forEach((FieldError t) -> {
            errors.add(t.getField() + ": " + t.getDefaultMessage());
        });//from  www.  j av  a2 s  .com
        return new ErrorResponse(mapper, HttpStatus.BAD_REQUEST, errors.toString(), null).response();
    }

    return response(_request, _authentication);
}

From source file:com.github.lynxdb.server.api.http.handlers.EpUser.java

@RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity createUser(Authentication _authentication, @RequestBody @Valid UserCreationRequest _ucr,
        BindingResult _bindingResult) {

    if (_bindingResult.hasErrors()) {
        ArrayList<String> errors = new ArrayList();
        _bindingResult.getFieldErrors().forEach((FieldError t) -> {
            errors.add(t.getField() + ": " + t.getDefaultMessage());
        });//  ww  w .j a  va 2 s  .c  o m
        return new ErrorResponse(mapper, HttpStatus.BAD_REQUEST, errors.toString()).response();
    }

    User u = new User(_ucr);

    if (users.create(u)) {
        return ResponseEntity.ok(u);
    } else {
        return new ErrorResponse(mapper, HttpStatus.BAD_REQUEST, "User already exists").response();
    }
}

From source file:com.github.lynxdb.server.api.http.handlers.EpUser.java

@RequestMapping(value = "/{userLogin}", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity updateUser(Authentication _authentication, @PathVariable("userLogin") String userLogin,
        @RequestBody @Valid UserUpdateRequest _ucr, BindingResult _bindingResult) {

    if (_bindingResult.hasErrors()) {
        ArrayList<String> errors = new ArrayList();
        _bindingResult.getFieldErrors().forEach((FieldError t) -> {
            errors.add(t.getField() + ": " + t.getDefaultMessage());
        });/* ww w . java 2 s .  c  om*/
        return new ErrorResponse(mapper, HttpStatus.BAD_REQUEST, errors.toString()).response();
    }

    User user = users.byLogin(userLogin);
    if (user == null) {
        return new ErrorResponse(mapper, HttpStatus.BAD_REQUEST, "User does not exist.", null).response();
    }

    if (_ucr.password != null && !_ucr.password.isEmpty()) {
        user.setPassword(_ucr.password);
    }
    if (_ucr.rank != null) {
        user.setRank(_ucr.rank);
    }

    users.save(user);

    return ResponseEntity.ok(user);
}

From source file:org.ng200.openolympus.controller.auth.RegistrationController.java

@RequestMapping(method = RequestMethod.POST)
public String registerUser(@Valid final UserDto userDto, final BindingResult bindingResult) {
    this.userDtoValidator.validate(userDto, bindingResult);
    if (bindingResult.hasErrors()) {
        RegistrationController.logger.info(bindingResult.getFieldErrors().toString());
        return "register";
    }/*w  w  w  .j a  va2 s.  c  o m*/

    if (this.userRepository.findByUsername(userDto.getUsername()) != null) {
        throw new IllegalStateException("Duplicate user should have been caught by validator!");
    }

    final User user = new User(userDto.getUsername(), this.passwordEncoder.encode(userDto.getPassword()),
            userDto.getFirstNameMain(), userDto.getMiddleNameMain(), userDto.getLastNameMain(),
            userDto.getFirstNameLocalised(), userDto.getMiddleNameLocalised(), userDto.getLastNameLocalised(),
            userDto.getTeacherFirstName(), userDto.getTeacherMiddleName(), userDto.getTeacherLastName(),
            userDto.getAddressLine1(), userDto.getAddressLine2(), userDto.getAddressCity(),
            userDto.getAddressState(), userDto.getAddressCountry(), userDto.getLandline(), userDto.getMobile(),
            userDto.getSchool(), userDto.getDateOfBirth());

    this.userRepository.save(user);

    return "redirect:/login";
}