Example usage for org.springframework.validation ValidationUtils rejectIfEmptyOrWhitespace

List of usage examples for org.springframework.validation ValidationUtils rejectIfEmptyOrWhitespace

Introduction

In this page you can find the example usage for org.springframework.validation ValidationUtils rejectIfEmptyOrWhitespace.

Prototype

public static void rejectIfEmptyOrWhitespace(Errors errors, String field, String errorCode) 

Source Link

Document

Reject the given field with the given error code if the value is empty or just contains whitespace.

Usage

From source file:net.solarnetwork.node.setup.web.NodeAssociationController.java

/**
 * Decode the invitation code, and present the decoded information for the
 * user to verify.//from   w w w. j  a  va 2s  .  co  m
 * 
 * @param command
 *        the command
 * @param errors
 *        the binding result
 * @param model
 *        the model
 * @return the view name
 */
@RequestMapping(value = "/preview", method = RequestMethod.POST)
public String previewInvitation(@ModelAttribute("command") AssociateNodeCommand command, Errors errors,
        Model model) {
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "verificationCode", "field.required");
    if (errors.hasErrors()) {
        return PAGE_ENTER_CODE;
    }

    try {
        NetworkAssociationDetails details = getSetupBiz().decodeVerificationCode(command.getVerificationCode());
        model.addAttribute(KEY_DETAILS, details);
    } catch (InvalidVerificationCodeException e) {
        errors.rejectValue("verificationCode", "verificationCode.invalid", null, null);
        return PAGE_ENTER_CODE;
    }
    return "associate/preview-invitation";
}

From source file:alfio.controller.form.PaymentForm.java

public void validate(BindingResult bindingResult, TotalPrice reservationCost, Event event,
        List<TicketFieldConfiguration> fieldConf) {

    List<PaymentProxy> allowedPaymentMethods = event.getAllowedPaymentProxies();

    Optional<PaymentProxy> paymentProxyOptional = Optional.ofNullable(paymentMethod);
    PaymentProxy paymentProxy = paymentProxyOptional.filter(allowedPaymentMethods::contains)
            .orElse(PaymentProxy.STRIPE);
    boolean priceGreaterThanZero = reservationCost.getPriceWithVAT() > 0;
    boolean multiplePaymentMethods = allowedPaymentMethods.size() > 1;
    if (multiplePaymentMethods && priceGreaterThanZero && !paymentProxyOptional.isPresent()) {
        bindingResult.reject(ErrorsCode.STEP_2_MISSING_PAYMENT_METHOD);
    } else if (priceGreaterThanZero
            && (paymentProxy == PaymentProxy.STRIPE && StringUtils.isBlank(stripeToken))) {
        bindingResult.reject(ErrorsCode.STEP_2_MISSING_STRIPE_TOKEN);
    }/*  ww  w  .  j a  va  2s  .  c  o  m*/

    if (Objects.isNull(termAndConditionsAccepted) || !termAndConditionsAccepted) {
        bindingResult.reject(ErrorsCode.STEP_2_TERMS_NOT_ACCEPTED);
    }

    email = StringUtils.trim(email);

    fullName = StringUtils.trim(fullName);
    firstName = StringUtils.trim(firstName);
    lastName = StringUtils.trim(lastName);

    billingAddress = StringUtils.trim(billingAddress);

    ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "email", ErrorsCode.STEP_2_EMPTY_EMAIL);
    rejectIfOverLength(bindingResult, "email", ErrorsCode.STEP_2_MAX_LENGTH_EMAIL, email, 255);

    if (event.mustUseFirstAndLastName()) {
        ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "firstName",
                ErrorsCode.STEP_2_EMPTY_FIRSTNAME);
        rejectIfOverLength(bindingResult, "firstName", ErrorsCode.STEP_2_MAX_LENGTH_FIRSTNAME, fullName, 255);
        ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "lastName", ErrorsCode.STEP_2_EMPTY_LASTNAME);
        rejectIfOverLength(bindingResult, "lastName", ErrorsCode.STEP_2_MAX_LENGTH_LASTNAME, fullName, 255);
    } else {
        ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "fullName", ErrorsCode.STEP_2_EMPTY_FULLNAME);
        rejectIfOverLength(bindingResult, "fullName", ErrorsCode.STEP_2_MAX_LENGTH_FULLNAME, fullName, 255);
    }

    rejectIfOverLength(bindingResult, "billingAddress", ErrorsCode.STEP_2_MAX_LENGTH_BILLING_ADDRESS,
            billingAddress, 450);

    if (email != null && !email.contains("@") && !bindingResult.hasFieldErrors("email")) {
        bindingResult.rejectValue("email", ErrorsCode.STEP_2_INVALID_EMAIL);
    }

    if (hasPaypalTokens() && !PaypalManager.isValidHMAC(new CustomerName(fullName, firstName, lastName, event),
            email, billingAddress, hmac, event)) {
        bindingResult.reject(ErrorsCode.STEP_2_INVALID_HMAC);
    }

    if (!postponeAssignment) {
        boolean success = Optional.ofNullable(tickets).filter(m -> !m.isEmpty()).map(m -> m.entrySet().stream()
                .map(e -> Validator.validateTicketAssignment(e.getValue(), fieldConf, Optional.empty(), event)))
                .filter(s -> s.allMatch(ValidationResult::isSuccess)).isPresent();
        if (!success) {
            bindingResult.reject(ErrorsCode.STEP_2_MISSING_ATTENDEE_DATA);
        }
    }
}

From source file:it.cilea.osd.jdyna.validator.ClassificazioneValidator.java

public void validateEditLevel(Object object, Errors errors) {

    DTOGestioneAlberoClassificatore classificazione = (DTOGestioneAlberoClassificatore) object;

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "editNome", "error.message.fallita.campo.obbligatorio");

    Integer albero = classificazione.getId();
    String codice = classificazione.getEditCodice();
    if (codice != null && albero != null) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "editCodice",
                "error.message.fallita.campo.obbligatorio");
        //controllo prima se il vecchio valore della classificazione 
        ValidationResult result = ((IValidatorClassificationService) getValidatorService())
                .controllaCodiceClassificazioneByIdAlberoIdClassificazioneCodice(albero,
                        classificazione.getEditID(), codice);
        if (!result.isSuccess()) {
            errors.rejectValue("editCodice", result.getMessage());
        }/*from   w  ww .  java  2 s  .com*/

    }
}

From source file:org.openmrs.module.personalhr.web.controller.ShortPatientValidator.java

/**
 * Validates the given Patient./*from   w w  w  . j  a  v a2s  .com*/
 * 
 * @param obj The patient to validate.
 * @param errors The patient to validate.
 * @see org.springframework.validation.Validator#validate(java.lang.Object,
 *      org.springframework.validation.Errors)
 * @should fail validation if gender is blank
 * @should fail validation if birthdate is blank
 * @should fail validation if birthdate makes patient older that 120 years old
 * @should fail validation if birthdate is a future date
 * @should fail validation if voidReason is blank when patient is voided
 * @should fail validation if causeOfDeath is blank when patient is dead
 */
@Override
public void validate(final Object obj, final Errors errors) {

    final ShortPatientModel shortPatientModel = (ShortPatientModel) obj;

    this.personNameValidator.validatePersonName(shortPatientModel.getName(), errors, false, false);

    // Make sure they choose a gender
    if (StringUtils.isBlank(shortPatientModel.getGender())) {
        errors.rejectValue("gender", "Person.gender.required");
    }

    // check patients birthdate against future dates and really old dates
    if (shortPatientModel.getBirthdate() != null) {
        if (shortPatientModel.getBirthdate().after(new Date())) {
            errors.rejectValue("birthdate", "error.date.future");
        } else {
            final Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.YEAR, -120); // patient cannot be older than 120 years old 
            if (shortPatientModel.getBirthdate().before(c.getTime())) {
                errors.rejectValue("birthdate", "error.date.nonsensical");
            }
        }
    } else {
        errors.rejectValue("birthdate", "error.required", new Object[] { "Birthdate" }, "");
    }

    /*
    PersonAttribute emailAttr = shortPatientModel.getAttributeMap().get("Email");
    if (emailAttr != null && !PersonalhrUtil.isNullOrEmpty((String) emailAttr.getHydratedObject())) {
       if(!PersonalhrUtil.isValidEmail(emailAttr.getValue())) {
       errors.reject("Invalid email address: |" + emailAttr.getHydratedObject() + "|" + emailAttr);               
       }
    } else {
    errors.reject("Email address cannot be empty! |" + emailAttr.getHydratedObject() + "|" + emailAttr);
    }      
    */

    //    Patient Info 
    if (shortPatientModel.getVoided()) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "voidReason", "error.null");
    }
    if (shortPatientModel.isDead() && (shortPatientModel.getCauseOfDeath() == null)) {
        errors.rejectValue("causeOfDeath", "Patient.dead.causeOfDeathNull");
    }

}

From source file:com.apress.progwt.server.web.domain.validation.CreateUserRequestValidator.java

/**
 * lookup messages from resource bundle//from ww w. j a va 2  s .  c  o m
 * 
 * NOTE: topicService.createUser() .lowerCases() the username
 */
public void validate(Object command, Errors errors) {

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "randomkey", "required");

    CreateUserRequestCommand comm = (CreateUserRequestCommand) command;

    log.info(comm.getOpenIDusername() + " " + comm.getUsername() + " " + comm.getRandomkey());

    boolean standard = comm.isStandard();
    boolean openID = comm.isOpenID();

    if (standard && openID) {
        errors.rejectValue("username", "invalid.username.both");
        errors.rejectValue("openIDusername", "invalid.username.both");
    }
    if (!standard && !openID) {
        errors.rejectValue("username", "invalid.username.oneorother");
        errors.rejectValue("openIDusername", "invalid.username.oneorother");
    }

    if (standard) {
        doStandardValidation(comm, errors);
    } else if (openID) {
        doOpenIDValidation(comm, errors);
    }

    if (!invitationService.isKeyValid(comm.getRandomkey())) {
        errors.rejectValue("randomkey", "invalid");
    }
    MailingListEntry entry = invitationService.getEntryForKey(comm.getRandomkey());
    if (entry != null && entry.getSignedUpUser() != null) {
        errors.rejectValue("randomkey", "invalid.randomkey.exists");
    }

}

From source file:org.motechproject.server.omod.web.controller.StaffController.java

@RequestMapping(method = RequestMethod.POST)
public String registerStaff(@ModelAttribute("staff") WebStaff staff, Errors errors, ModelMap model) {

    log.debug("Register Staff");

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "motechmodule.firstName.required");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "motechmodule.lastName.required");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "type", "motechmodule.staffType.required");

    validateTextLength(errors, "firstName", staff.getFirstName(), MotechConstants.MAX_STRING_LENGTH_OPENMRS);
    validateTextLength(errors, "lastName", staff.getLastName(), MotechConstants.MAX_STRING_LENGTH_OPENMRS);
    validateTextLength(errors, "phone", staff.getPhone(), MotechConstants.MAX_STRING_LENGTH_OPENMRS);

    if (staff.getPhone() != null && !staff.getPhone().matches(MotechConstants.PHONE_REGEX_PATTERN)) {
        errors.rejectValue("phone", "motechmodule.phoneNumber.invalid");
    }//from   w ww .ja va 2 s.c om

    if (!errors.hasErrors()) {
        User user = registrarBean.registerStaff(staff.getFirstName(), staff.getLastName(), staff.getPhone(),
                staff.getType(), staff.getStaffId());
        model.addAttribute("successMsg", (staff.isNew() ? NEW : EDIT).message(user));
    }
    model.addAttribute("staffTypes", registrarBean.getStaffTypes());
    return "/module/motechmodule/staff";
}

From source file:alfio.util.Validator.java

public static ValidationResult validateTicketAssignment(UpdateTicketOwnerForm form,
        List<TicketFieldConfiguration> additionalFieldsForEvent, Optional<Errors> errorsOptional, Event event) {
    if (!errorsOptional.isPresent()) {
        return ValidationResult.success();//already validated
    }//from   w  ww.j a  v  a  2s. c  o  m
    Errors errors = errorsOptional.get();
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "error.email");
    String email = form.getEmail();
    if (!isEmailValid(email)) {
        errors.rejectValue("email", "error.email");
    }

    if (event.mustUseFirstAndLastName()) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", ErrorsCode.STEP_2_EMPTY_FIRSTNAME);
        validateMaxLength(form.getFirstName(), "firstName", ErrorsCode.STEP_2_MAX_LENGTH_FIRSTNAME, 255,
                errors);

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", ErrorsCode.STEP_2_EMPTY_LASTNAME);
        validateMaxLength(form.getLastName(), "lastName", ErrorsCode.STEP_2_MAX_LENGTH_LASTNAME, 255, errors);
    } else {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "fullName", ErrorsCode.STEP_2_EMPTY_FULLNAME);
        validateMaxLength(form.getFullName(), "fullName", ErrorsCode.STEP_2_MAX_LENGTH_FULLNAME, 255, errors);
    }

    //
    for (TicketFieldConfiguration fieldConf : additionalFieldsForEvent) {

        boolean isField = form.getAdditional() != null && form.getAdditional().containsKey(fieldConf.getName());

        if (!isField) {
            continue;
        }

        form.getAdditional().get(fieldConf.getName()).forEach(formValue -> {
            if (fieldConf.isMaxLengthDefined()) {
                validateMaxLength(formValue, "additional['" + fieldConf.getName() + "']",
                        "error." + fieldConf.getName(), fieldConf.getMaxLength(), errors);
            }

            if (!fieldConf.getRestrictedValues().isEmpty()) {
                validateRestrictedValue(formValue, "additional['" + fieldConf.getName() + "']",
                        "error." + fieldConf.getName(), fieldConf.getRestrictedValues(), errors);
            }

            if (fieldConf.isRequired() && StringUtils.isBlank(formValue)) {
                errors.rejectValue("additional['" + fieldConf.getName() + "']", "error." + fieldConf.getName());
            }
        });

        //TODO: complete checks: min length
    }

    return evaluateValidationResult(errors);
}

From source file:it.cilea.osd.jdyna.validator.ClassificazioneValidator.java

public void validateSubLevel(Object object, Errors errors) {

    DTOGestioneAlberoClassificatore classificazione = (DTOGestioneAlberoClassificatore) object;

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "subNome", "error.message.fallita.campo.obbligatorio");

    Integer albero = classificazione.getId();
    String codice = classificazione.getSubCodice();
    if (codice != null && albero != null) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "subCodice",
                "error.message.fallita.campo.obbligatorio");
        ValidationResult result = ((IValidatorClassificationService) getValidatorService())
                .controllaCodiceClassificazioneByIdAlberoECodice(albero, codice);
        if (!result.isSuccess()) {
            errors.rejectValue("subCodice", result.getMessage());
        }//from  w  w  w  .  ja  v  a2s . co m

    }
}

From source file:org.openmrs.web.controller.encounter.EncounterFormController.java

/**
 * @see org.springframework.web.servlet.mvc.SimpleFormController#processFormSubmission(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 *///from w w w.j  ava  2 s.  c o  m
@Override
protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse reponse,
        Object obj, BindException errors) throws Exception {

    Encounter encounter = (Encounter) obj;

    try {
        if (Context.isAuthenticated()) {
            Context.addProxyPrivilege(PrivilegeConstants.GET_USERS);
            Context.addProxyPrivilege(PrivilegeConstants.GET_PATIENTS);

            if (encounter.getEncounterId() == null && StringUtils.hasText(request.getParameter("patientId"))) {
                encounter.setPatient(Context.getPatientService()
                        .getPatient(Integer.valueOf(request.getParameter("patientId"))));
            }
            if (encounter.isVoided()) {
                ValidationUtils.rejectIfEmptyOrWhitespace(errors, "voidReason", "error.null");
            }

            String[] providerIdsArray = ServletRequestUtils.getStringParameters(request, "providerIds");
            if (ArrayUtils.isEmpty(providerIdsArray)) {
                errors.reject("Encounter.provider.atleastOneProviderRequired");
            }

            String[] roleIdsArray = ServletRequestUtils.getStringParameters(request, "encounterRoleIds");

            ProviderService ps = Context.getProviderService();
            EncounterService es = Context.getEncounterService();
            if (providerIdsArray != null && roleIdsArray != null) {
                //list to store role provider mappings to be used below to detect removed providers
                List<String> unremovedRoleAndProviders = new ArrayList<String>();
                for (int i = 0; i < providerIdsArray.length; i++) {
                    if (StringUtils.hasText(providerIdsArray[i]) && StringUtils.hasText(roleIdsArray[i])) {
                        unremovedRoleAndProviders.add(roleIdsArray[i] + "-" + providerIdsArray[i]);
                        Provider provider = ps.getProvider(Integer.valueOf(providerIdsArray[i]));
                        EncounterRole encounterRole = es.getEncounterRole(Integer.valueOf(roleIdsArray[i]));
                        //if this is an existing provider, don't create a new one to avoid losing existing
                        //details like dateCreated, creator, uuid etc in the encounter_provider table
                        if (encounter.getProvidersByRole(encounterRole).contains(provider)) {
                            continue;
                        }

                        //this is a new provider
                        encounter.addProvider(encounterRole, provider);
                    }
                }
                //Get rid of the removed ones
                for (Map.Entry<EncounterRole, Set<Provider>> entry : encounter.getProvidersByRoles()
                        .entrySet()) {
                    for (Provider p : entry.getValue()) {
                        if (!unremovedRoleAndProviders
                                .contains(entry.getKey().getEncounterRoleId() + "-" + p.getProviderId())) {
                            encounter.removeProvider(entry.getKey(), p);
                        }
                    }
                }
            }

            ValidationUtils.invokeValidator(new EncounterValidator(), encounter, errors);
        }
    } finally {
        Context.removeProxyPrivilege(PrivilegeConstants.GET_USERS);
        Context.removeProxyPrivilege(PrivilegeConstants.GET_PATIENTS);
    }

    return super.processFormSubmission(request, reponse, encounter, errors);
}

From source file:com.ccserver.digital.validator.CreditCardApplicationValidator.java

private void validateEmploymentTab(CreditCardApplicationDTO creditCardApplicationDTO, Errors errors) {
    if (creditCardApplicationDTO.getTypeOfEmployement() == TypeOfEmployment.Business) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "licenseNumber", ErrorCodes.FIELD_REQUIRED);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "businessStartDate", ErrorCodes.FIELD_REQUIRED);
        if (creditCardApplicationDTO.getBusinessStartDate() != null) {
            if (creditCardApplicationDTO.getBusinessStartDate().isAfter(LocalDateTime.now())) {
                errors.rejectValue("businessStartDate", ErrorCodes.FIELD_NOT_FUTURE);
            }/*from w w w.j a  v  a  2s  .com*/
        }
        ValidationUtils.rejectIfEmpty(errors, "businessPhone", ErrorCodes.FIELD_REQUIRED);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "businessAddress", ErrorCodes.FIELD_REQUIRED);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "companyName", ErrorCodes.FIELD_REQUIRED);

    } else {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "nameOfEmployer", ErrorCodes.FIELD_REQUIRED);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "occupation", ErrorCodes.FIELD_REQUIRED);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "industry", ErrorCodes.FIELD_REQUIRED);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "employerAddress", ErrorCodes.FIELD_REQUIRED);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "businessTelephone", ErrorCodes.FIELD_REQUIRED);

        if ((creditCardApplicationDTO.getMonthsOfWorking() == null
                || creditCardApplicationDTO.getMonthsOfWorking() == 0)
                && (creditCardApplicationDTO.getYearsOfWorking() == null
                        || creditCardApplicationDTO.getYearsOfWorking() == 0)) {
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "monthsOfWorking", ErrorCodes.FIELD_REQUIRED);
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "yearsOfWorking", ErrorCodes.FIELD_REQUIRED);
        }
    }

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "monthlyIncome", ErrorCodes.FIELD_REQUIRED);
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "monthlyExpenses", ErrorCodes.FIELD_REQUIRED);

    if (creditCardApplicationDTO.getMonthlyExpenses() != null && creditCardApplicationDTO.getMonthlyExpenses()
            .compareTo(creditCardApplicationDTO.getMonthlyIncome()) > 0) {
        errors.rejectValue("monthlyExpenses", ErrorCodes.FIELD_INVALID);
    }
}