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(String field);

Source Link

Document

Get all errors associated with the given field.

Usage

From source file:com.mitchellbosecke.pebble.spring.extension.function.bindingresult.GetFieldErrorsFunction.java

@Override
public Object execute(Map<String, Object> args) {
    List<String> results = new ArrayList<>();
    String formName = (String) args.get(PARAM_FORM_NAME);
    String field = (String) args.get(PARAM_FIELD_NAME);

    if (field == null) {
        throw new IllegalArgumentException("Field parameter is required in GetFieldErrorsFunction");
    }/*from w  ww .  j  a  v a2s .c  om*/

    EvaluationContext context = (EvaluationContext) args.get("_context");
    Locale locale = context.getLocale();
    BindingResult bindingResult = this.getBindingResult(formName, context);

    if (bindingResult != null) {
        for (FieldError error : bindingResult.getFieldErrors(field)) {
            String msg = this.messageSource.getMessage(error.getCode(), error.getArguments(),
                    error.getDefaultMessage(), locale);
            if (msg != null) {
                results.add(msg);
            }
        }
    }
    return results;
}

From source file:com.autoupdater.server.controllers.FrontEndAPIController.java

/**
 * Handles errors that occurred during remote upload.
 * /*from www . j  a v a  2  s.  c  om*/
 * @param response
 *            response to send
 * @param result
 *            result of validation
 */
private void handleErrorDuringRemoteUpload(HttpServletResponse response, BindingResult result) {
    int errorCode;
    List<FieldError> errors;

    if (result.hasFieldErrors("username")) {
        errorCode = SC_UNAUTHORIZED;
        errors = result.getFieldErrors("username");
    } else if (result.hasFieldErrors("program")) {
        errorCode = SC_FORBIDDEN;
        errors = result.getFieldErrors("username");
    } else {
        errorCode = SC_BAD_REQUEST;
        errors = result.getFieldErrors();
    }

    StringBuilder builder = new StringBuilder();
    for (FieldError error : errors)
        builder.append(error.getDefaultMessage()).append('\n');
    sendError(response, errorCode, builder.toString());
}

From source file:eu.scidipes.toolkits.pawebapp.web.ItemsController.java

@RequestMapping(value = { "/edit", "/{formID}/edit", "/new" }, method = RequestMethod.POST)
public String saveItem(@ModelAttribute final SaveAction saveAction, @ModelAttribute final Form form,
        final BindingResult result, final SessionStatus status, final RedirectAttributes redirectAttrs,
        @RequestPart(value = "dataHolder", required = false) final MultipartFile dataFile,
        @MatrixVariable(value = "fn", required = false, pathVar = "datasetName") final String formName) {

    formValidator.validate(form, result);
    if (result.hasErrors()) {
        boolean fixErrors = true;

        final List<FieldError> dataHolderErrors = result.getFieldErrors("dataHolder");

        /*//from   ww w . ja va 2  s .c om
         * Only ignore errors under very specific conditions, i.e. when there is a single no-file-supplied error and
         * a current file exists
         */
        if (result.getErrorCount() == 1 && dataHolderErrors != null && dataHolderErrors.size() == 1) {

            final FieldError dataHolderError = dataHolderErrors.get(0);
            if (FormValidator.FILE_REQ_ERR_CODE.equals(dataHolderError.getCode())
                    && !form.getDataHolderMetadata().isEmpty() && form.getDataHolderType() == BYTESTREAM) {
                fixErrors = false;
            }

        }

        if (fixErrors) {
            return "datasets/items/edit";
        }
    }

    /* Ensure that the dataHolder field is not overwritten when its an empty upload (i.e. re-save) */
    if (form.getDataHolderType() == BYTESTREAM && dataFile != null && !dataFile.isEmpty()) {
        LOG.debug("incoming dataFile: {}", dataFile);
        form.getDataHolderMetadata().put(FILE_NAME, dataFile.getOriginalFilename());
        form.getDataHolderMetadata().put(FILE_SIZE, String.valueOf(dataFile.getSize()));
        form.getDataHolderMetadata().put(FILE_MIMETYPE, dataFile.getContentType());
    } else if (form.getDataHolderType() == URI && !StringUtils.isEmpty(form.getDataHolder())) {
        LOG.debug("incoming dataHolder: {}", form.getDataHolder());
        form.getDataHolderMetadata().clear();
    }

    final FormsBundleImpl dataset = datasetRepo.findOne(form.getParentBundle().getDatasetName());

    if (saveAction == ADD_NEW) {
        dataset.addForm(form);
    } else {
        dataset.setForm(form);
    }

    final FormsBundle savedDataset = datasetRepo.save(dataset);
    final Form savedForm = savedDataset.getForms().get(savedDataset.getForms().indexOf(form));

    status.setComplete();
    redirectAttrs.addFlashAttribute("msgKey", "items.edit.messages.savesuccess");

    final String formNameMatrixVar = StringUtils.isEmpty(formName) ? "" : ";fn=" + formName;
    return "redirect:/datasets/" + savedDataset.getDatasetName() + formNameMatrixVar + "/items/"
            + savedForm.getFormID() + "/edit";
}

From source file:org.jtalks.jcommune.web.controller.PostController.java

/**
 * Prepare ModelAndView for showing preview
 *
 * @return prepared ModelAndView for preview
 *//*from  ww  w  .  j a  v a2  s  .  com*/
private ModelAndView getPreviewModelAndView(BindingResult result) {
    return new ModelAndView("ajax/postPreview").addObject("isInvalid", result.hasFieldErrors("bodyText"))
            .addObject("errors", result.getFieldErrors("bodyText"));
}