Example usage for org.springframework.validation ValidationUtils rejectIfEmpty

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

Introduction

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

Prototype

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

Source Link

Document

Reject the given field with the given error code if the value is empty.

Usage

From source file:com.pkrete.locationservice.admin.validator.UserInfoValidator.java

@Override
public void validate(Object target, Errors errors) {
    UserInfo info = (UserInfo) target;// w ww  . j  a v a2  s .c o  m
    ValidationUtils.rejectIfEmpty(errors, "user.firstName", "error.user.firstname.required");
    ValidationUtils.rejectIfEmpty(errors, "user.lastName", "error.user.lastname.required");
    ValidationUtils.rejectIfEmpty(errors, "user.username", "error.user.username.required");
    ValidationUtils.rejectIfEmpty(errors, "user.email", "error.user.email.required");
    ValidationUtils.rejectIfEmpty(errors, "user.organization", "error.user.organization.required");

    if (info.getUser().getFirstName().length() > 100) {
        errors.rejectValue("user.firstName", "error.user.firstname.length");
    }

    if (info.getUser().getLastName().length() > 100) {
        errors.rejectValue("user.lastName", "error.user.lastname.length");
    }

    if (info.getUser().getUsername().length() > 15) {
        errors.rejectValue("user.username", "error.user.username.length");
    }

    if (info.getUser().getEmail().length() > 100) {
        errors.rejectValue("user.email", "error.user.email.length");
    }

    if (info.getUser().getOrganization().length() > 100) {
        errors.rejectValue("user.organization", "error.user.organization.length");
    }

    if (info.getUser().getPasswordUi().length() > 100) {
        errors.rejectValue("user.passwordUi", "error.user.password.length");
    }

    if (info.getUser().getPasswordControl().length() > 100) {
        errors.rejectValue("user.passwordControl", "error.user.password.length");
    }

    if (!info.getUser().getEmail().isEmpty()) {
        if (!WebUtil.validateEmail(info.getUser().getEmail())) {
            errors.rejectValue("user.email", "error.user.email.invalid");
        }
    }

    if (info.getUser().getPassword().isEmpty()) {
        if (info.getUser().getPasswordUi().isEmpty() && info.getUser().getPasswordControl().isEmpty()) {
            errors.rejectValue("user.passwordUi", "error.user.password.required");
        }
    }

    if (!info.getUser().getPasswordUi().equals(info.getUser().getPasswordControl())) {
        errors.rejectValue("user.passwordUi", "error.user.password.match");
        if (info.getUser().getPasswordControl().isEmpty()) {
            errors.rejectValue("user.passwordControl", "error.user.password.confirmation.required");
        }
    }

    if (!info.getUser().getPasswordUi().isEmpty()
            && info.getUser().getPasswordUi().length() < this.passwordMinLength) {
        errors.rejectValue("user.passwordUi", "error.userinfo.password.new.length");
    }

    if (info.getGroup() == null) {
        errors.rejectValue("group", "error.user.usergroup.required");
    }
    if (info.getUser().getOwner() == null) {
        errors.rejectValue("user.owner", "error.user.password.owner.required");
    }
    if (info.getId() == 0) {
        if (usersService.getUser(info.getUser().getUsername()) != null) {
            errors.rejectValue("user.username", "error.user.username.exist");
        }
    } else {
        User temp = usersService.getUser(info.getUser().getUsername());
        if (temp != null) {
            UserInfo tempInfo = usersService.getUserInfoByUsername(temp.getUsername());
            if (!info.equals(tempInfo)) {
                errors.rejectValue("user.username", "error.user.username.exist");
            }
        }

    }
}

From source file:org.tonguetied.web.UserValidator.java

/**
 * This validation method checks if the password and re-entered password
 * match and confirm to a valid format./* w  ww .  jav  a  2s.  c o  m*/
 * 
 * @param user the {@link User} object to validate
 * @param errors contextual state about the validation process (never null)
 */
private void validatePassword(final User user, Errors errors) {
    // check for duplicates of new records only
    if (user.getId() == null) {
        ValidationUtils.rejectIfEmpty(errors, FIELD_USER_PASSWORD, "error.password.required");
        if (user.getPassword() != null) {
            if (!user.getPassword().equals(user.getRepeatedPassword()))
                errors.rejectValue(FIELD_USER_REPEATED_PASSWORD, "error.password.mismatch");
        }
    }
}

From source file:com.pkrete.locationservice.admin.validator.MapValidator.java

@Override
public void validate(Object target, Errors errors) {
    ValidationUtils.rejectIfEmpty(errors, "description", "error.map.description");

    Map map = (Map) target;

    if (map.getFilePath() != null) {
        if (map.getFilePath().length() > 500) {
            errors.rejectValue("path", "error.illustration.path.length");
        }/*from w  ww  . j av a  2 s.  com*/
    }

    if (map.getUrl() != null) {
        if (map.getUrl().length() > 500) {
            errors.rejectValue("url", "error.illustration.path.length");
        }
    }

    if (map.getDescription().length() > 100) {
        errors.rejectValue("description", "error.illustration.desc.length");
    }

    if (map.getColor().length() > 6) {
        errors.rejectValue("color", "error.illustration.color.length");
    }

    if (map.getOpacity().length() > 3) {
        errors.rejectValue("opacity", "error.illustration.opacity.length");
    }

    boolean filePathNull = false;
    if (map.getFilePath() == null) {
        map.setFilePath("");
        filePathNull = true;
    }
    if (map.getUrl() == null) {
        map.setUrl("");
    }

    if (map.getOwner() == null) {
        errors.rejectValue("description", "error.map.owner");
    }

    if (!map.getColor().isEmpty()) {
        if (map.getColor().length() != 6 && map.getColor().length() != 3) {
            errors.rejectValue("color", "error.map.color.length");
        } else if (!WebUtil.validateHexColor(map.getColor())) {
            errors.rejectValue("color", "error.map.color.form");
        }
    }

    if (!map.getOpacity().isEmpty()) {
        String temp = map.getOpacity();
        try {
            int opacityInt = this.converterService.strToInt(temp);
            temp = Integer.toString(opacityInt);
        } catch (NumberFormatException nfe) {
            temp = "255";
        }
        map.setOpacity(temp);
        if (map.getOpacity().length() < 1 && map.getOpacity().length() > 3) {
            errors.rejectValue("opacity", "error.map.opacity.length");
        } else if (!map.getOpacity().matches("^\\d+$")) {
            errors.rejectValue("opacity", "error.map.opacity.form");
        } else if (this.converterService.strToInt(map.getOpacity()) > 255
                || this.converterService.strToInt(map.getOpacity()) < 0) {
            errors.rejectValue("opacity", "error.map.opacity.value");
        }
    }

    if (map.getFiles() == null && filePathNull) {
        if (map.getUrl().length() == 0) {
            errors.rejectValue("path", "error.map.url.required");
        } else if (!WebUtil.validateUrl(map.getUrl())) {
            errors.rejectValue("path", "error.map.url.bad");
        } else if (!WebUtil.exists(map.getUrl())) {
            errors.rejectValue("path", "error.map.url.exist");
        }
    } else if (map.getFiles() != null && map.getId() == 0) {
        if (map.getFilePath().length() == 0 && map.getUrl().length() == 0 && !map.hasFile()) {
            errors.rejectValue("path", "error.map.one_required");
        } else if (map.getFilePath().length() > 0 && map.getUrl().length() > 0 && map.hasFile()) {
            errors.rejectValue("path", "error.map.only_one");
        } else if (map.getFilePath().length() > 0 && map.hasFile()) {
            errors.rejectValue("path", "error.map.only_one");
        } else if (map.getFilePath().length() > 0 && map.getUrl().length() > 0) {
            errors.rejectValue("path", "error.map.only_one");
        } else if (map.getUrl().length() > 0 && map.hasFile()) {
            errors.rejectValue("path", "error.map.only_one");
        } else if (map.getUrl().length() > 0) {
            if (!WebUtil.validateUrl(map.getUrl())) {
                errors.rejectValue("url", "error.map.url.bad");
            } else if (!WebUtil.exists(map.getUrl())) {
                errors.rejectValue("url", "error.map.url.exist");
            }
        } else if (!map.hasFiles() && map.hasFile()) {
            errors.rejectValue("path", "error.map.file.missing");
        } else if (map.hasFiles()) {
            java.util.Map<Integer, MultipartFile> files = map.getFiles();
            for (Entry<Integer, MultipartFile> entry : files.entrySet()) {
                String name = entry.getValue().getOriginalFilename().toLowerCase();
                if (!name.matches(".*\\.(jpg|png|gif|bmp)$")) {
                    errors.rejectValue("files[" + entry.getKey() + "]", "error.map.file.format.invalid");
                }
            }
            if (files.size() > 1) {
                List<MultipartFile> list = map.getFilesList();
                for (int i = 0; i < list.size() - 1; i++) {
                    String file1 = list.get(i).getOriginalFilename();
                    String file2 = list.get(i + 1).getOriginalFilename();
                    int length = file1.length();
                    if (!file2.endsWith(file1.substring(length - 3, length))) {
                        errors.rejectValue("path", "error.map.file.format.different");
                    }
                }
            }
        }
    } else if (map.getFiles() != null && map.getId() > 0) {
        java.util.Map<Integer, MultipartFile> files = map.getFiles();
        for (Entry<Integer, MultipartFile> entry : files.entrySet()) {
            String name = entry.getValue().getOriginalFilename().toLowerCase();
            if (name.length() > 0) {
                if (!name.matches(".*\\.(jpg|png|gif|bmp)$")) {
                    errors.rejectValue("files[" + entry.getKey() + "]", "error.map.file.format.invalid");
                }
            }
        }

        if (files.size() > 1) {
            String ending = "";
            for (Entry<Integer, MultipartFile> entry : files.entrySet()) {
                if (entry.getValue().getOriginalFilename().length() > 0) {
                    int length = entry.getValue().getOriginalFilename().length();
                    ending = entry.getValue().getOriginalFilename().substring(length - 3, length);
                    break;
                }
            }
            for (Entry<Integer, MultipartFile> entry : files.entrySet()) {
                if (entry.getValue().getOriginalFilename().length() > 0) {
                    if (!entry.getValue().getOriginalFilename().endsWith(ending)
                            || !map.getPath().endsWith(ending)) {
                        errors.rejectValue("files[" + entry.getKey() + "]", "error.map.file.format.different");
                    }
                }
            }
        }
    }
}

From source file:com.pkrete.locationservice.admin.validator.SimplifiedMapValidator.java

@Override
public void validate(Object target, Errors errors) {
    // Regex for validating the file type
    String fileTypeRegex = ".*\\.(jpg|png|gif|bmp)$";

    ValidationUtils.rejectIfEmpty(errors, "description", "error.map.description");

    Map map = (Map) target;

    boolean filePathNullOrEmpty = map.getFilePath() != null && !map.getFilePath().isEmpty() ? false : true;
    boolean urlNullOrEmpty = map.getUrl() != null && !map.getUrl().isEmpty() ? false : true;
    boolean filesNullOrEmpty = map.getFiles() != null && map.hasFile() ? false : true;

    int count = getCount(filePathNullOrEmpty, urlNullOrEmpty, filesNullOrEmpty);

    if (!filePathNullOrEmpty && map.getFilePath().length() > 500) {
        errors.rejectValue("path", "error.illustration.path.length");
    }/*from   ww w.  j  a v  a2 s.  co m*/

    if (!urlNullOrEmpty && map.getUrl().length() > 500) {
        errors.rejectValue("url", "error.illustration.path.length");
    }

    if (map.getDescription().length() > 100) {
        errors.rejectValue("description", "error.illustration.desc.length");
    }

    if (map.getColor().length() > 6) {
        errors.rejectValue("color", "error.illustration.color.length");
    }

    if (map.getOpacity().length() > 3) {
        errors.rejectValue("opacity", "error.illustration.opacity.length");
    }

    if (map.getOwner() == null) {
        errors.rejectValue("description", "error.map.owner");
    }

    if (!map.getColor().isEmpty()) {
        if (map.getColor().length() != 6 && map.getColor().length() != 3) {
            errors.rejectValue("color", "error.map.color.length");
        } else if (!WebUtil.validateHexColor(map.getColor())) {
            errors.rejectValue("color", "error.map.color.form");
        }
    }

    if (!map.getOpacity().isEmpty()) {
        try {
            Integer.parseInt(map.getOpacity());
        } catch (NumberFormatException nfe) {
            errors.rejectValue("opacity", "error.map.opacity.form");
        }
        if (map.getOpacity().length() < 1 && map.getOpacity().length() > 3) {
            errors.rejectValue("opacity", "error.map.opacity.length");
        } else if (this.converterService.strToInt(map.getOpacity()) > 255
                || this.converterService.strToInt(map.getOpacity()) < 0) {
            errors.rejectValue("opacity", "error.map.opacity.value");
        }
    }

    // If id is 0 the map is new, and it must have files or url
    if (map.getId() == 0 && count == 0) {
        errors.rejectValue("path", "error.map.one_required");
    } else if (count == 0 && map.getIsExternal()) {
        // External map must have a URL
        errors.rejectValue("url", "error.map.url.required");
    } else if (count > 1) {
        // Map can not have more than one file or url
        errors.rejectValue("path", "error.map.only_one");
    } else if (count == 1) {
        if (!filePathNullOrEmpty) {
            if (map.getId() == 0 || map.getIsExternal()) {
                if (!this.mapsService.adminMapExists(map.getFilePath(), map.getOwner())) {
                    errors.rejectValue("path", "error.map.file.bad.multi");
                }
            } else {
                List<Language> list = null;
                if (!this.mapsService.adminMapExists(map.getFilePath(), list, map.getOwner())) {
                    errors.rejectValue("path", "error.map.file.bad.single");
                }
            }
            if (!map.getFilePath().toLowerCase().matches(fileTypeRegex)) {
                errors.rejectValue("path", "error.map.file.format.invalid");
            } else if (map.getId() != 0 && !map.getIsExternal()) {
                // Get file type of the current file
                int length = map.getPath().length();
                String ending = map.getPath().substring(length - 3, length);
                // Check that the file type matches with the current type
                if (!ending.isEmpty() && !map.getFilePath().endsWith(ending)) {
                    errors.rejectValue("path", "error.map.file.format.original");
                }
            }
        } else if (!filesNullOrEmpty) {
            if (map.getId() == 0) {
                if (!map.hasFiles() && map.hasFile()) {
                    errors.rejectValue("path", "error.map.file.missing");
                } else {
                    // Check that all the files are of the same type
                    List<MultipartFile> list = map.getFilesList();
                    for (int i = 0; i < list.size() - 1; i++) {
                        String file1 = list.get(i).getOriginalFilename();
                        String file2 = list.get(i + 1).getOriginalFilename();
                        int length = file1.length();
                        if (!file2.endsWith(file1.substring(length - 3, length))) {
                            errors.rejectValue("path", "error.map.file.format.different");
                        }
                    }
                }
            }
            // Get file type of the current file
            int length = map.getPath() == null ? 0 : map.getPath().length();
            String ending = map.getPath() != null && map.getPath().matches(fileTypeRegex)
                    ? map.getPath().substring(length - 3, length)
                    : "";
            // Go through all the files
            java.util.Map<Integer, MultipartFile> files = map.getFiles();
            for (Entry<Integer, MultipartFile> entry : files.entrySet()) {
                if (entry.getValue() != null && entry.getValue().getSize() > 0) {
                    String name = entry.getValue().getOriginalFilename().toLowerCase();
                    // Check that the file type is valid
                    if (!name.matches(fileTypeRegex)) {
                        errors.rejectValue("files[" + entry.getKey() + "]", "error.map.file.format.invalid");
                    }
                    if (map.getId() > 0) {
                        // Check that the file type matches with the current type
                        if (!ending.isEmpty() && !entry.getValue().getOriginalFilename().endsWith(ending)) {
                            errors.rejectValue("files[" + entry.getKey() + "]",
                                    "error.map.file.format.original");
                        }
                    }
                }
            }
        } else if (!urlNullOrEmpty) {
            if (!WebUtil.validateUrl(map.getUrl())) {
                errors.rejectValue("url", "error.map.url.bad");
            } else if (!WebUtil.exists(map.getUrl())) {
                errors.rejectValue("url", "error.map.url.exist");
            }
        }
    }
}

From source file:org.openmrs.module.radiology.order.RadiologyOrderValidator.java

/**
 * Checks the form object for any inconsistencies/errors
 *
 * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
 * @should fail validation if radiologyOrder is null
 * @should fail validation if voided is null
 * @should fail validation if concept is null
 * @should fail validation if patient is null
 * @should fail validation if orderer is null
 * @should fail validation if urgency is null
 * @should fail validation if action is null
 * @should fail validation if dateActivated after dateStopped
 * @should fail validation if dateActivated after autoExpireDate
 * @should fail validation if scheduledDate is set and urgency is not set as ON_SCHEDULED_DATE
 * @should fail validation if scheduledDate is null when urgency is ON_SCHEDULED_DATE
 * @should pass validation if all fields are correct
 * @should not allow a future dateActivated
 *//*from ww w  . ja  v  a 2 s.co  m*/
public void validate(Object obj, Errors errors) {
    final RadiologyOrder radiologyOrder = (RadiologyOrder) obj;
    if (radiologyOrder == null) {
        errors.reject("error.general");
    } else {
        // for the following elements Order.hbm.xml says: not-null="true"
        ValidationUtils.rejectIfEmpty(errors, "voided", "error.null");
        ValidationUtils.rejectIfEmpty(errors, "concept", "Concept.noConceptSelected");
        ValidationUtils.rejectIfEmpty(errors, "patient", "error.null");
        ValidationUtils.rejectIfEmpty(errors, "orderer", "error.null");
        ValidationUtils.rejectIfEmpty(errors, "urgency", "error.null");
        ValidationUtils.rejectIfEmpty(errors, "action", "error.null");
        // Order.encounter and
        // Order.orderType
        // have not null constraint as well, but are set in RadiologyOrderService.saveRadiologyOrder
        validateDateActivated(radiologyOrder, errors);
        validateScheduledDate(radiologyOrder, errors);
    }
}

From source file:org.openmrs.web.controller.report.RunReportController.java

public void validate(Object commandObject, Errors errors) {
    CommandObject command = (CommandObject) commandObject;
    ValidationUtils.rejectIfEmpty(errors, "schema", "Missing reportId, or report not found");
    if (command.getSchema() != null) {
        ReportSchema rs = command.getSchema();
        Set<String> requiredParams = new HashSet<String>();
        if (rs.getReportParameters() != null) {
            for (Parameter p : rs.getReportParameters()) {
                if (p.isRequired())
                    requiredParams.add(p.getName());
            }/*from www  .j  a  v a  2s . c o m*/
        }

        for (Map.Entry<String, String> e : command.getUserEnteredParams().entrySet()) {
            if (StringUtils.hasText(e.getValue()))
                requiredParams.remove(e.getKey());
        }
        if (requiredParams.size() > 0) {
            errors.rejectValue("userEnteredParams", "Enter all parameter values");
        }

        if (rs.getDataSetDefinitions() == null || rs.getDataSetDefinitions().size() == 0)
            errors.rejectValue("schema", "ReportSchema must declare some data set definitions");
    }
    ValidationUtils.rejectIfEmpty(errors, "selectedRenderer", "Pick a renderer");
}

From source file:org.openmrs.module.bom.web.controller.BomRunReportFormController.java

@Override
public void validate(Object commandObject, Errors errors) {
    CommandObject command = (CommandObject) commandObject;
    ValidationUtils.rejectIfEmpty(errors, "reportDefinition", "reporting.Report.run.error.missingReportID");
    if (command.getReportDefinition() != null) {
        ReportDefinition reportDefinition = command.getReportDefinition();
        Set<String> requiredParams = new HashSet<String>();
        if (reportDefinition.getParameters() != null) {
            for (Parameter parameter : reportDefinition.getParameters()) {
                if (parameter.isRequired()) {
                    requiredParams.add(parameter.getName());
                }/*from   w w  w. j  a v a 2 s . c  o m*/
            }
        }

        for (Map.Entry<String, Object> e : command.getUserEnteredParams().entrySet()) {
            if (e.getValue() instanceof Iterable || e.getValue() instanceof Object[]) {
                Object iterable = e.getValue();
                if (e.getValue() instanceof Object[]) {
                    iterable = Arrays.asList((Object[]) e.getValue());
                }

                boolean hasNull = true;

                for (Object value : (Iterable<Object>) iterable) {
                    hasNull = !ObjectUtil.notNull(value);
                }

                if (!hasNull) {
                    requiredParams.remove(e.getKey());
                }
            } else if (ObjectUtil.notNull(e.getValue())) {
                requiredParams.remove(e.getKey());
            }
        }
        if (requiredParams.size() > 0) {
            for (Iterator<String> iterator = requiredParams.iterator(); iterator.hasNext();) {
                String parameterName = (String) iterator.next();
                if (StringUtils.hasText(command.getExpressions().get(parameterName))) {
                    String expression = command.getExpressions().get(parameterName);
                    if (!EvaluationUtil.isExpression(expression)) {
                        errors.rejectValue("expressions[" + parameterName + "]",
                                "reporting.Report.run.error.invalidParamExpression");
                    }
                } else {
                    errors.rejectValue("userEnteredParams[" + parameterName + "]", "error.required",
                            new Object[] { "This parameter" }, "{0} is required");
                }
            }
        }

        if (reportDefinition.getDataSetDefinitions() == null
                || reportDefinition.getDataSetDefinitions().size() == 0) {
            errors.reject("reporting.Report.run.error.definitionNotDeclared");
        }

        if (ObjectUtil.notNull(command.getSchedule())) {
            if (!CronExpression.isValidExpression(command.getSchedule())) {
                errors.rejectValue("schedule", "reporting.Report.run.error.invalidCronExpression");
            }
        }
    }
    ValidationUtils.rejectIfEmpty(errors, "selectedRenderer", "reporting.Report.run.error.noRendererSelected");
}

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

private void validateMobilephone(CreditCardApplicationDTO creditCardApplicationDTO, Errors errors) {
    // validate empty
    ValidationUtils.rejectIfEmpty(errors, "mobile", ErrorCodes.FIELD_REQUIRED);
    ValidationUtils.rejectIfEmpty(errors, "mobile.phoneNumber", ErrorCodes.FIELD_REQUIRED);
    PhoneDTO mobile = creditCardApplicationDTO.getMobile();
    if (mobile != null) {
        // validate existing
        CreditCardApplicationDTO ccAppExisting = creditCardApplicationService.findByMobile(mobile);
        if (ccAppExisting != null && ccAppExisting.getId() != creditCardApplicationDTO.getId()) {
            errors.rejectValue("mobile", ErrorCodes.FIELD_EXISTING);

        }//w  w w. ja v a 2s  .  co  m
    }
}

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

@RequestMapping(method = RequestMethod.POST)
public String submitForm(@ModelAttribute("enrollpatient") WebPatient webPatient, Errors errors, ModelMap model,
        SessionStatus status, HttpSession session) {

    log.debug("Enroll Demo Patient");

    ValidationUtils.rejectIfEmpty(errors, "motechId", "motechmodule.motechId.required");

    Patient patient = null;/*from w  w  w  .  j a v  a2 s.co m*/
    if (webPatient.getMotechId() != null) {
        patient = openmrsBean.getPatientByMotechId(webPatient.getMotechId().toString());
        if (patient == null) {
            errors.rejectValue("motechId", "motechmodule.motechId.notexist");
        }
    }

    if (!Boolean.TRUE.equals(webPatient.getConsent())) {
        errors.rejectValue("consent", "motechmodule.consent.required");
    }

    if (!errors.hasErrors()) {
        registrarBean.demoEnrollPatient(patient);

        model.addAttribute("successMsg", "motechmodule.Demo.Patient.enroll.success");

        status.setComplete();

        session.removeAttribute("demoLastMotechId");

        return "redirect:/module/motechmodule/demo-success.htm";
    }

    return "/module/motechmodule/demo-enrollpatient";
}