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.validator.PrivilegeValidator.java

/**
 * Checks the form object for any inconsistencies/errors
 * //  w w  w . j  av a2 s  .  c  o  m
 * @see org.springframework.validation.Validator#validate(java.lang.Object,
 *      org.springframework.validation.Errors)
 * @should fail validation if privilege is null or empty or whitespace
 * @should pass validation if description is null or empty or whitespace
 * @should pass validation if all required fields have proper values
 * @should pass validation if field lengths are correct
 * @should fail validation if field lengths are not correct
 */
public void validate(Object obj, Errors errors) {
    Privilege privilege = (Privilege) obj;
    if (privilege == null) {
        errors.rejectValue("privilege", "error.general");
    } else {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "privilege", "error.privilege");
        ValidateUtil.validateFieldLengths(errors, obj.getClass(), "privilege", "description");
    }
}

From source file:org.openmrs.validator.ProgramValidator.java

/**
 * Checks the form object for any inconsistencies/errors
 * //  ww w  . j  av a 2 s  . com
 * @see org.springframework.validation.Validator#validate(java.lang.Object,
 *      org.springframework.validation.Errors)
 * @should fail validation if name is null or empty or whitespace
 * @should pass validation if description is null or empty or whitespace
 * @should fail validation if program name already in use
 * @should fail validation if concept is null or empty or whitespace
 * @should pass validation if all required fields have proper values
 * @should pass validation and save edited program
 * @should pass validation if field lengths are correct
 * @should fail validation if field lengths are not correct
 */
public void validate(Object obj, Errors errors) {
    Program p = (Program) obj;
    if (p == null) {
        errors.rejectValue("program", "error.general");
    } else {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "error.name");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "concept", "error.concept");

        Program existingProgram = Context.getProgramWorkflowService().getProgramByName(p.getName());
        if (existingProgram != null && !existingProgram.getUuid().equals(p.getUuid())) {
            errors.rejectValue("name", "general.error.nameAlreadyInUse");
        }
        if (existingProgram != null && existingProgram.getUuid().equals(p.getUuid())) {
            Context.evictFromSession(existingProgram);
        }
        ValidateUtil.validateFieldLengths(errors, obj.getClass(), "name");
    }
}

From source file:org.openmrs.validator.RelationshipTypeValidator.java

/**
 * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
 * @should fail validation if aIsToB(or A is To B) is null or empty or whitespace
 * @should fail validation if bIsToA(or B is To A) is null or empty or whitespace
 * @should fail validation if description is null or empty or whitespace
 * @should pass validation if all required fields are set
 * @should fail validation if relationshipTypeName already exist
 * @should pass validation if field lengths are correct
 * @should fail validation if field lengths are not correct
 *///  w  w w.  ja v a2s .  c  om
public void validate(Object obj, Errors errors) {
    RelationshipType relationshipType = (RelationshipType) obj;
    if (relationshipType == null) {
        errors.rejectValue("relationshipType", "error.general");
    } else {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "aIsToB", "RelationshipType.aIsToB.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "bIsToA", "RelationshipType.bIsToA.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "description",
                "RelationshipType.description.required");
        RelationshipType exist = Context.getPersonService()
                .getRelationshipTypeByName(relationshipType.getaIsToB() + "/" + relationshipType.getbIsToA());
        if (exist != null && !exist.isRetired()
                && !OpenmrsUtil.nullSafeEquals(relationshipType.getUuid(), exist.getUuid())) {
            errors.reject("duplicate.relationshipType");
        }
        ValidateUtil.validateFieldLengths(errors, obj.getClass(), "aIsToB", "bIsToA", "description",
                "retireReason");
    }
}

From source file:org.openmrs.validator.ReportObjectValidator.java

/**
 * Checks the form object for any inconsistencies/errors
 * //from   w  w  w  .  ja v  a  2  s  .  c o m
 * @see org.springframework.validation.Validator#validate(java.lang.Object,
 *      org.springframework.validation.Errors)
 */
public void validate(Object obj, Errors errors) {

    if (obj instanceof AbstractReportObject) {
        AbstractReportObject reportObject = (AbstractReportObject) obj;
        if (reportObject == null) {
            errors.rejectValue("report object", "error.general");
        } else {
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "error.name");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "type", "error.reportObject.type.required");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "subType", "error.reportObject.subType.required");
        }
    } else {
        errors.rejectValue("report object", "error.general");
    }
}

From source file:org.openmrs.validator.RoleValidator.java

/**
 * Checks the form object for any inconsistencies/errors
 * //from  w w w .  jav  a2  s.c  om
 * @see org.springframework.validation.Validator#validate(java.lang.Object,
 *      org.springframework.validation.Errors)
 * @should throw NullPointerException if role is null
 * @should fail validation if role is empty or whitespace
 * @should pass validation if description is null or empty or whitespace
 * @should fail validation if role has leading or trailing space
 * @should pass validation if all required fields have proper values
 * @should pass validation if field lengths are correct
 * @should fail validation if field lengths are not correct
 */
public void validate(Object obj, Errors errors) {
    Role role = (Role) obj;
    if (role == null) {
        errors.rejectValue("role", "error.general");
    } else {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "role", "error.role");

        // reject any role that has a leading or trailing space
        if (!role.getRole().equals(role.getRole().trim())) {
            errors.rejectValue("role", "error.trailingSpaces");
        }
    }
    if (obj == null) {
        throw new IllegalArgumentException("validated role object should not be null");
    } else {
        ValidateUtil.validateFieldLengths(errors, obj.getClass(), "role", "description");
    }
}

From source file:org.openmrs.validator.StateConversionValidator.java

/**
 * Checks the form object for any inconsistencies/errors
 * /*w  w w .ja va 2s.c  om*/
 * @see org.springframework.validation.Validator#validate(java.lang.Object,
 *      org.springframework.validation.Errors)
 * @should fail validation if concept is null or empty or whitespace
 * @should fail validation if programWorkflow is null or empty or whitespace
 * @should fail validation if programWorkflowState is null or empty or whitespace
 * @should pass validation if all required fields have proper values
 */
public void validate(Object obj, Errors errors) {
    ConceptStateConversion c = (ConceptStateConversion) obj;
    if (c == null) {
        log.debug("Rejecting because c is null");
        errors.rejectValue("conceptStateConversion", "error.general");
    } else {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "concept", "error.concept");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "programWorkflow", "error.programWorkflow");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "programWorkflowState", "error.programWorkflowState");
    }
}

From source file:org.openmrs.validator.VisitAttributeTypeValidator.java

/**
 * Checks the form object for any inconsistencies/errors
 * //  w  w w. j  a va  2s  .  c om
 * @see org.springframework.validation.Validator#validate(java.lang.Object,
 *      org.springframework.validation.Errors)
 * @should fail validation if name is null or empty or whitespace
 * @should fail validation if description is null or empty or whitespace
 * @should pass validation if all required fields have proper values
 */
public void validate(Object obj, Errors errors) {
    VisitAttributeType visitAttributeType = (VisitAttributeType) obj;
    if (visitAttributeType == null) {
        errors.reject("error.general");
    } else {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "error.name");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "minOccurs", "error.null");

        Integer minOccurs = visitAttributeType.getMinOccurs();
        Integer maxOccurs = visitAttributeType.getMaxOccurs();

        if (minOccurs != null) {
            if (minOccurs < 0) {
                errors.rejectValue("minOccurs", "AttributeType.minOccursShouldNotBeLessThanZero");
            }
        }

        if (maxOccurs != null) {
            if (maxOccurs < 0) {
                errors.rejectValue("maxOccurs", "AttributeType.maxOccursShouldNotBeLessThanZero");
            } else if (maxOccurs < minOccurs) {
                errors.rejectValue("maxOccurs", "AttributeType.maxOccursShouldNotBeLessThanMinOccurs");
            }
        }
    }
}

From source file:org.openmrs.validator.VisitTypeValidator.java

/**
 * Checks the form object for any inconsistencies/errors
 * /*from  w  ww  . j  a va2  s .  c om*/
 * @see org.springframework.validation.Validator#validate(java.lang.Object,
 *      org.springframework.validation.Errors)
 * @should fail validation if name is null or empty or whitespace
 * @should fail validation if description is null or empty or whitespace
 * @should pass validation if all required fields have proper values
 * @should pass validation if field lengths are correct
 * @should fail validation if field lengths are not correct
 */
public void validate(Object obj, Errors errors) {
    VisitType visitType = (VisitType) obj;
    if (visitType == null) {
        errors.rejectValue("visitType", "error.general");
    } else {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "error.name");
        ValidateUtil.validateFieldLengths(errors, obj.getClass(), "name", "description", "retireReason");
    }
}

From source file:org.openmrs.web.controller.patient.NewPatientFormController.java

protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response,
        Object obj, BindException errors) throws Exception {

    newIdentifiers = new HashSet<PatientIdentifier>();

    ShortPatientModel shortPatient = (ShortPatientModel) obj;

    log.debug("\nNOW GOING THROUGH PROCESSFORMSUBMISSION METHOD.......................................\n\n");

    if (Context.isAuthenticated()) {
        PatientService ps = Context.getPatientService();
        MessageSourceAccessor msa = getMessageSourceAccessor();

        String action = request.getParameter("action");
        if (action == null || action.equals(msa.getMessage("general.save"))) {
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name.familyName", "error.name");

            String[] identifiers = request.getParameterValues("identifier");
            String[] types = request.getParameterValues("identifierType");
            String[] locs = request.getParameterValues("location");
            pref = request.getParameter("preferred");
            if (pref == null)
                pref = "";

            if (log.isDebugEnabled()) {
                log.debug("identifiers: " + identifiers);
                for (String s : identifiers)
                    log.debug(s);//ww w  . j a  va 2  s  .  c o m
                log.debug("types: " + types);
                for (String s : types)
                    log.debug(s);
                log.debug("locations: " + locs);
                for (String s : locs)
                    log.debug(s);
                log.debug("preferred: " + pref);
            }

            // loop over the identifiers to create the patient.identifiers set
            if (identifiers != null) {
                for (int i = 0; i < identifiers.length; i++) {
                    // arguments for the spring error messages
                    String id = identifiers[i].trim();
                    String[] args = { id };

                    // add the new identifier only if they put in some identifier string
                    if (id.length() > 0) {

                        // set up the actual identifier java object
                        PatientIdentifierType pit = null;
                        if (types[i] == null || types[i].equals("")) {
                            String msg = getMessageSourceAccessor()
                                    .getMessage("PatientIdentifier.identifierType.null", args);
                            errors.reject(msg);
                        } else
                            pit = ps.getPatientIdentifierType(Integer.valueOf(types[i]));

                        Location loc = null;
                        if (locs[i] == null || locs[i].equals("")) {
                            String msg = getMessageSourceAccessor()
                                    .getMessage("PatientIdentifier.location.null", args);
                            errors.reject(msg);
                        } else
                            loc = Context.getLocationService().getLocation(Integer.valueOf(locs[i]));

                        PatientIdentifier pi = new PatientIdentifier(id, pit, loc);
                        pi.setPreferred(pref.equals(id + types[i]));
                        if (newIdentifiers.contains(pi))
                            newIdentifiers.remove(pi);

                        //                     pi.setUuid(null);
                        newIdentifiers.add(pi);

                        if (log.isDebugEnabled()) {
                            log.debug("Creating patient identifier with identifier: " + id);
                            log.debug("and type: " + types[i]);
                            log.debug("and location: " + locs[i]);
                        }

                    }
                }
            }
        }

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "gender", "error.null");

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

    }

    // skip calling super.processFormSubmission so that setting up the page is done
    // again in the onSubmit method

    return onSubmit(request, response, shortPatient, errors);
}

From source file:org.openmrs.web.controller.patient.ShortPatientValidator.java

/**
 * Validates the given Patient./*from  ww w  .j ava2s .  co m*/
 * 
 * @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
 */
public void validate(Object obj, Errors errors) {

    ShortPatientModel shortPatientModel = (ShortPatientModel) obj;

    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 {
            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" }, "");
    }

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

}