Example usage for org.springframework.validation BindingResult addError

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

Introduction

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

Prototype

void addError(ObjectError error);

Source Link

Document

Add a custom ObjectError or FieldError to the errors list.

Usage

From source file:info.gehrels.voting.web.VoteBuilder.java

public void validate(String objectName, String fieldPrefix, BindingResult bindingResult) {
    if (type == VoteType.PREFERENCE) {
        if (allNullOrEmpty(preferencesByCandidateIdx)) {
            bindingResult.addError(new FieldError(objectName, fieldPrefix + ".preferencesByCandidateIdx", "",
                    true, new String[] { "emptyPreference" }, new Object[] {},
                    "You must enter a preference if you have selected it."));
        } else if (containsDuplicates(preferencesByCandidateIdx)) {
            bindingResult.addError(new FieldError(objectName, fieldPrefix + ".preferencesByCandidateIdx", "",
                    true, new String[] { "duplicatesInPreference" }, new Object[] {},
                    "You must enter a duplicate free preference."));
        }//w  ww  .jav  a2s . c o  m
    } else {
        if (!allNullOrEmpty(preferencesByCandidateIdx)) {
            bindingResult.addError(new FieldError(objectName, fieldPrefix + ".preferencesByCandidateIdx", "",
                    true, new String[] { "noPreferenceAllowed" }, new Object[] {},
                    "You must not enter a preference for no, invalid or non casted votes."));
        }
    }
}

From source file:ch.rasc.wampspring.method.PayloadArgumentResolver.java

@Override
public Object resolveArgument(MethodParameter param, Message<?> message) throws Exception {
    Payload ann = param.getParameterAnnotation(Payload.class);
    if (ann != null && StringUtils.hasText(ann.value())) {
        throw new IllegalStateException("@Payload SpEL expressions not supported by this resolver");
    }//from ww w  . ja v a2 s. c om

    Object payload = message.getPayload();
    if (isEmptyPayload(payload)) {
        if (ann == null || ann.required()) {
            String paramName = getParameterName(param);
            BindingResult bindingResult = new BeanPropertyBindingResult(payload, paramName);
            bindingResult.addError(new ObjectError(paramName, "@Payload param is required"));
            throw new MethodArgumentNotValidException(message, param, bindingResult);
        }
        return null;
    }

    Class<?> targetClass = param.getParameterType();
    if (ClassUtils.isAssignable(targetClass, payload.getClass())) {
        validate(message, param, payload);
        return payload;
    }

    payload = this.methodParameterConverter.convert(param, message.getPayload());
    if (payload == null) {
        throw new MessageConversionException(message,
                "No converter found to convert to " + targetClass + ", message=" + message);
    }

    validate(message, param, payload);
    return payload;
}

From source file:com.stormpath.tooter.controller.LoginController.java

@RequestMapping(method = RequestMethod.GET)
public String initForm(@ModelAttribute("customer") User customer, BindingResult result, ModelMap model) {
    try {/*from   w w  w  .ja v  a  2s. c  om*/
        stormpath.getTenant();
    } catch (Throwable t) {
        result.addError(new ObjectError("userName",
                "You have not finished configuring this sample application. "
                        + "Please follow the <a href=\"https://github.com/stormpath/stormpath-spring-samples/wiki/Tooter\">"
                        + "Set-up Instructions</a>"));
        t.printStackTrace();
    }

    model.addAttribute("customer", customer);

    //return form view
    return "login";
}

From source file:com.sjsu.bikelet.web.TenantLicensePolicyController.java

private void validateDate(BindingResult bindingResult, TenantLicensePolicy tenantLicensePolicy) {

    if (tenantLicensePolicy.getLicenseEndDate() == null
            || !tenantLicensePolicy.getLicenseEndDate().after(tenantLicensePolicy.getLicenseStartDate())) {
        bindingResult.addError(
                new ObjectError("tenantLicensePolicy", "License Start Date must be before license End Date"));
    } else if (!CollectionUtils
            .isEmpty(tenantLicensePolicyService.verifyLicensePolicyDates(tenantLicensePolicy))) {
        bindingResult.addError(new ObjectError("tenantLicensePolicy",
                "New license start date and end date must supersede existing ones"));
    }//from w  w w. j a va2  s . co  m

}

From source file:com.mylaensys.dhtmlx.adapter.test.TestForm.java

@Test
public void errorFormAdapter() throws Exception {

    BindingResult binding = new BeanPropertyBindingResult(object, "object");

    DefaultFormAdapter adapter = new DefaultFormAdapter(object, binding);
    adapter.serialize(Locale.getDefault());

    /* Adds an error */
    binding.addError(new FieldError("object", "date", "error"));
    DefaultFormAdapter adapterWithErrors = new DefaultFormAdapter(object, binding);
    adapterWithErrors.serialize(Locale.getDefault());

}

From source file:com.sopovs.moradanen.fan.controller.SignupController.java

@RequestMapping(value = "/signup", method = RequestMethod.POST)
public String signup(@Valid SignupData signupData, BindingResult bindingResult, ModelMap modelMap,
        WebRequest request) {/*from w w  w  .j  ava2  s.  com*/
    if (!userDetailService.checkUsernameNotUsed(signupData.getUserName())) {
        bindingResult.addError(new FieldError("registrationData", "userName", signupData.getUserName(), false,
                null, null, "username already in use"));
    }
    if (!userDetailService.checkVisibleNameNotUsed(signupData.getVisibleName())) {
        bindingResult.addError(new FieldError("registrationData", "visibleName", signupData.getVisibleName(),
                false, null, null, "visible name already in use"));
    }

    if (bindingResult.hasErrors()) {
        modelMap.put("signupData", signupData);
        return "chooseUserName";
    }
    User newUser = signupData.createUser();
    userDetailService.saveUser(newUser);
    SignInUtils.signin(newUser.getId().toString());
    providerSignInUtils.doPostSignUp(newUser.getId().toString(), request);

    return "redirect:/";

}

From source file:nl.surfnet.coin.selfservice.control.requests.LinkrequestController.java

/**
 * BACKLOG-1128: Impersonating users (as a 'super user') cannot really submit the request/question they're about to submit.
 * Those are caught here, adding an error to the BindingResult, resulting in the error displayed in the view.
 * @param result the BindingResult, to which an error will be added if needed
 *//*from   ww  w .  j a  v a 2  s.  co  m*/
private void denySuperUser(BindingResult result) {
    if (SpringSecurity.getCurrentUser().getAuthorityEnums()
            .contains(CoinAuthority.Authority.ROLE_DASHBOARD_SUPER_USER)) {
        result.addError(new ObjectError("superuser.impersonation", new String[] { "superuser.impersonation" },
                null, "Impersonated: cannot submit"));
    }
}

From source file:org.energyos.espi.datacustodian.web.custodian.UploadController.java

@RequestMapping(value = Routes.DATA_CUSTODIAN_UPLOAD, method = RequestMethod.POST)
public String uploadPost(@ModelAttribute UploadForm uploadForm, BindingResult result)
        throws IOException, JAXBException {

    try {//from w  w w.  j  a  va2s .  c o  m

        importService.importData(uploadForm.getFile().getInputStream(), null);
        return "redirect:/custodian/retailcustomers";

    } catch (SAXException e) {

        result.addError(new ObjectError("uploadForm", e.getMessage()));
        return "/custodian/upload";

    } catch (Exception e) {

        result.addError(new ObjectError("uploadForm", "Unable to process file"));
        return "/custodian/upload";
    }
}

From source file:org.kew.rmf.matchconf.web.CustomConfigController.java

public void customValidation(Configuration config, BindingResult br) {
    // validation for all classes that have their name as part of a REST-ish url
    if (!FieldValidator.validSlug(config.getName())) {
        br.addError(new ObjectError("config.name",
                "The name has to be set and can only contain ASCII letters and/or '-' and/or '_'"));
    }/*  w w  w.  j  av a 2s .co m*/
    // MatchConfig specific: has to specify a authorityFileName
    if (config.getClassName().equals("MatchConfiguration") && config.getAuthorityFileName().equals("")) {
        br.addError(new ObjectError("configuration.authorityFileName",
                "A Match Configuration needs to specify an authority File"));
    }
}

From source file:com.stormpath.tooter.controller.LoginController.java

@RequestMapping(method = RequestMethod.GET, value = "/emailVerificationTokens")
public String accountVerification(@RequestParam("sptoken") String token,
        @ModelAttribute("customer") User customer, BindingResult result) {

    String returnStr = "login";

    try {/*from   w  ww  . j ava2 s  . c o  m*/

        stormpath.getTenant().verifyAccountEmail(token);
        returnStr = "redirect:/login/message?loginMsg=accVerified";

    } catch (RuntimeException re) {

        result.addError(new ObjectError("userName", re.getMessage()));
        re.printStackTrace();
    }

    return returnStr;

}