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:org.openmrs.web.controller.concept.ConceptStopWordFormController.java

/**
 * Handle the add new ConceptStopWord/*from w  ww . java2  s .  c  om*/
 *
 * @param httpSession
 * @param conceptStopWord
 * @param errors
 * @return path to forward to or an error message
 * @should add new ConceptStopWord
 * @should return error message if a duplicate ConceptStopWord is added
 * @should return error message for an empty ConceptStopWord
 */
@RequestMapping(method = RequestMethod.POST)
public String handleSubmission(HttpSession httpSession,
        @ModelAttribute("command") ConceptStopWord conceptStopWord, BindingResult errors) {

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "value", "ConceptStopWord.error.value.empty");

    if (errors.hasErrors()) {
        return showForm();
    }

    try {
        Context.getConceptService().saveConceptStopWord(conceptStopWord);
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "ConceptStopWord.saved");
    } catch (ConceptStopWordException e) {
        log.error("Error on adding concept stop word", e);
        httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, e.getMessage());
        return showForm();
    }

    return "redirect:conceptStopWord.list";
}

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

public void validateIdeaComments(Object object, Errors errors) {
    IdeaComment ideaComment = (IdeaComment) object;

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, IDEA_KEY, IdeaExchangeConstants.Messages.REQUIRED_FIELD);
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, TEXT, IdeaExchangeConstants.Messages.REQUIRED_FIELD);
    if (StringUtils.length(ideaComment.getText()) > COMMENT_LENGTH) {
        errors.rejectValue(TEXT, IdeaExchangeErrorCodes.COMMENT_LENGTH_EXCEEDS,
                IdeaExchangeConstants.Messages.COMMENT_LENGTH_EXCEEDS);
    }/*from   ww  w.j  a  va2 s. c om*/

    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:com.epam.training.storefront.forms.validation.PaymentDetailsValidator.java

@Override
public void validate(final Object object, final Errors errors) {
    final PaymentDetailsForm form = (PaymentDetailsForm) object;

    final Calendar start = parseDate(form.getStartMonth(), form.getStartYear());
    final Calendar expiration = parseDate(form.getExpiryMonth(), form.getExpiryYear());
    final Calendar current = Calendar.getInstance();

    if (start != null) {
        if (start.after(current)) {
            errors.rejectValue("startMonth", "payment.startDate.past.invalid");
        }/*ww  w . ja v  a2s .co m*/

        if (expiration != null) {
            if (start.after(expiration)) {
                errors.rejectValue("startMonth", "payment.startDate.invalid");
            }
        }
    }

    if (expiration != null) {
        if (expiration.before(current)) {
            errors.rejectValue("expiryMonth", "payment.expiryDate.future.invalid");
        }
    }

    final boolean editMode = StringUtils.isNotBlank(form.getPaymentId());
    if (editMode || Boolean.TRUE.equals(form.getNewBillingAddress())) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "billingAddress.firstName",
                "address.firstName.invalid");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "billingAddress.lastName",
                "address.lastName.invalid");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "billingAddress.line1", "address.line1.invalid");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "billingAddress.townCity",
                "address.townCity.invalid");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "billingAddress.postcode",
                "address.postcode.invalid");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "billingAddress.countryIso",
                "address.country.invalid");
    }
}

From source file:com.virtusa.akura.common.validator.SportSubValidator.java

/**
 * Validates the object of the SportSub.
 * //from   ww  w  .jav a2 s . c  om
 * @param object - Populated object of SportSub to validate
 * @param err - Errors object that is building. May contain errors for the fields relating to types.
 */
@Override
public void validate(Object object, Errors err) {

    ValidationUtils.rejectIfEmptyOrWhitespace(err, DESCRIPTION_EIELD, ERROR_DESCRIPTION_REQUIRED);

    SportSub sportSub = (SportSub) object;
    String validatorPattern = ValidatorExpressionUtil.getValidatorPattern(SPORTS_SUB_VALIDATOR);
    Pattern alphaNumericOnly = Pattern.compile(validatorPattern);

    String descript = sportSub.getDescription().trim();
    String description = descript.replaceAll(" ", "");
    Matcher makeMatch = alphaNumericOnly.matcher(description);

    if (makeMatch.find()) {
        err.rejectValue(DESCRIPTION_EIELD, ERROR_SPORTSUB_TYPE);
    }
}

From source file:com.acc.validator.CCPaymentInfoValidator.java

@Override
public void validate(final Object target, final Errors errors) {
    final CCPaymentInfoData ccPaymentData = (CCPaymentInfoData) target;

    if (StringUtils.isNotBlank(ccPaymentData.getStartMonth())
            && StringUtils.isNotBlank(ccPaymentData.getStartYear())
            && StringUtils.isNotBlank(ccPaymentData.getExpiryMonth())
            && StringUtils.isNotBlank(ccPaymentData.getExpiryYear())) {
        final Calendar start = Calendar.getInstance();
        start.set(Calendar.DAY_OF_MONTH, 0);
        start.set(Calendar.MONTH, Integer.parseInt(ccPaymentData.getStartMonth()) - 1);
        start.set(Calendar.YEAR, Integer.parseInt(ccPaymentData.getStartYear()) - 1);

        final Calendar expiration = Calendar.getInstance();
        expiration.set(Calendar.DAY_OF_MONTH, 0);
        expiration.set(Calendar.MONTH, Integer.parseInt(ccPaymentData.getExpiryMonth()) - 1);
        expiration.set(Calendar.YEAR, Integer.parseInt(ccPaymentData.getExpiryYear()) - 1);

        if (start.after(expiration)) {
            errors.rejectValue("startMonth", "payment.startDate.invalid");
        }/*from   www  .  j a  v  a  2s  .  c  om*/
    }

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "accountHolderName", "field.required");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "cardType", "field.required");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "cardNumber", "field.required");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "expiryMonth", "field.required");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "expiryYear", "field.required");

    paymentAddressValidator.validate(ccPaymentData, errors);
}

From source file:com.virtusa.akura.common.validator.ClubSocietyValidator.java

/**
 * Validates the object of the ClubSociety.
 *
 * @param object - Populated object of ClubSociety to validate
 * @param err - Errors object that is building. May contain errors for the fields relating to types.
 *//*from w w  w.j ava2  s.  co m*/
@Override
public void validate(Object object, Errors err) {

    ValidationUtils.rejectIfEmptyOrWhitespace(err, FIELD_NAME, AkuraWebConstant.MANDATORY_FIELD_ERROR_CODE);
    ClubSociety clubSociety = (ClubSociety) object;
    Pattern stringOnly = Pattern
            .compile(ValidatorExpressionUtil.getValidatorPattern(REFERENCE_CLUBANDSOCIETY_VALIDATOR));
    String name = clubSociety.getName().trim();
    // String strName = name.replaceAll(" ", "");
    Matcher makeMatch = stringOnly.matcher(name);
    if (makeMatch.find()) {
        err.rejectValue(FIELD_NAME, AkuraWebConstant.MISMATCH_ERROR);
    }
    if (clubSociety.getDescription().length() > MAXIMUM_LENGTH_OF_DESCRIPTION) {
        err.rejectValue(DESCRIPTION_FIELD_NAME, AkuraWebConstant.DESCRIPTION_LENGTH_ERROR);
    }

}

From source file:com.virtusa.akura.student.validator.WarningLevelValidator.java

/**
 * Validates the object of the WarningLevel.
 * //from  w w w.  ja  v a2  s.c  o  m
 * @param target - Populated object of WarningLevel to validate
 * @param errors - Errors object that is building. May contain errors for the fields relating to types.
 */

public void validate(Object target, Errors errors) {

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, DESCRIPTION, REF_UI_WARNINGLEVEL_DESCRIPTION_REQUIRED);

    WarningLevel warningLevel = (WarningLevel) target;
    String description = warningLevel.getDescription().trim();

    Pattern stringOnly = Pattern
            .compile(ValidatorExpressionUtil.getValidatorPattern(STUDENT_WARNINGLEVEL_VALIDATOR));
    String descrip = description.replaceAll(" ", "");

    Matcher makeMapDesceription = stringOnly.matcher(descrip);

    if (makeMapDesceription.find()) {
        errors.rejectValue(DESCRIPTION, REF_UI_WARNING_FIELD_INVALID);
    }

}

From source file:com.virtusa.akura.student.validator.PrefectTypeValidator.java

/**
 * Validates the object of the PrefectType.
 *
 * @param target - Populated object of PrefectType to validate
 * @param errors - Errors object that is building. May contain errors for the fields relating to types.
 *///from  www .j  av  a 2 s  . c o m
public void validate(Object target, Errors errors) {

    // required field
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, DESCRIPTION, REF_UI_PREFECTTYPE_DESCRIPTION_REQUIRED);
    PrefectType prefectType = (PrefectType) target;
    String description = prefectType.getDescription().trim();

    Pattern stringOnly = Pattern
            .compile(ValidatorExpressionUtil.getValidatorPattern(STUDENT_PREFECTTYPE_VALIDATOR));
    String descrip = description.replaceAll(" ", "");

    Matcher makeMatch = stringOnly.matcher(descrip);
    if (makeMatch.find()) {
        errors.rejectValue(DESCRIPTION, REF_UI_PREFECT_FIELD_INVALID);
    }
}

From source file:org.openmrs.module.adminui.page.controller.metadata.locations.LocationAttributeTypePageController.java

public String post(PageModel model,
        @RequestParam(value = "locationAttributeTypeId", required = false) @BindParams LocationAttributeType locationAttributeType,
        @SpringBean("locationService") LocationService locationService, HttpServletRequest request) {

    Errors errors = new BeanPropertyBindingResult(locationAttributeType, "locationAttributeType");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "adminui.field.required");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "datatypeClassname", "adminui.field.required");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "minOccurs", "adminui.field.required");
    if (locationAttributeType.getMinOccurs() == null) {
        locationAttributeType.setMinOccurs(0);
    }/*from   w ww  .j a v  a  2s  . co  m*/

    if (!errors.hasErrors()) {
        ValidateUtil.validate(locationAttributeType, errors);
    }

    if (!errors.hasErrors()) {
        try {
            locationService.saveLocationAttributeType(locationAttributeType);
            InfoErrorMessageUtil.flashInfoMessage(request.getSession(),
                    "adminui.locationAttributeType.save.success");
            return "redirect:/adminui/metadata/locations/manageLocationAttributeTypes.page";
        } catch (Exception e) {
            log.error("Failed to save location attribute type:", e);
            request.getSession().setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE,
                    "adminui.locationAttributeType.save.fail");
        }
    }

    model.addAttribute("errors", errors);
    model.addAttribute("locationAttributeType", locationAttributeType);
    model.addAttribute("datatypesMap", getDatatypes());
    model.addAttribute("handlersMap", getHandlers());

    return "metadata/locations/locationAttributeType";
}