Example usage for org.apache.commons.validator GenericValidator minLength

List of usage examples for org.apache.commons.validator GenericValidator minLength

Introduction

In this page you can find the example usage for org.apache.commons.validator GenericValidator minLength.

Prototype

public static boolean minLength(String value, int min) 

Source Link

Document

Checks if the value's length is greater than or equal to the min.

Usage

From source file:jp.primecloud.auto.api.util.ValidateUtil.java

/**
 *
 * ??/*from   w w  w .  j  a v a 2s . c  om*/
 *
 * @param value ??
 * @param minLength ??
 * @param maxLength ?
 * @param code ??
 * @param params ??
 */
public static void lengthInRange(String value, int minLength, int maxLength, String code, Object[] params) {
    if (value != null) {
        if (GenericValidator.minLength(value, minLength) == false
                || GenericValidator.maxLength(value, maxLength) == false) {
            throw new AutoApplicationException(code, params);
        }
    }
}

From source file:com.primeleaf.krystal.web.action.cpanel.NewUserAction.java

public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL);

    if (request.getMethod().equalsIgnoreCase("POST")) {

        String realName = request.getParameter("txtRealName") != null ? request.getParameter("txtRealName")
                : "";
        String userName = request.getParameter("txtUserName") != null ? request.getParameter("txtUserName")
                : "";
        String password = request.getParameter("txtPassWord") != null ? request.getParameter("txtPassWord")
                : "";
        String confirmPassword = request.getParameter("txtConfirmPassWord") != null
                ? request.getParameter("txtConfirmPassWord")
                : "";
        String userEmail = request.getParameter("txtUserEmail") != null ? request.getParameter("txtUserEmail")
                : "";
        String userDescription = request.getParameter("txtDescription") != null
                ? request.getParameter("txtDescription")
                : "";
        String userType = request.getParameter("radUserType") != null ? request.getParameter("radUserType")
                : "A";

        userName = userName.replace(' ', '_');

        try {/*from www . ja v  a 2  s. c  o  m*/
            if (!GenericValidator.matchRegexp(userName, HTTPConstants.ALPHA_REGEXP)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input for User Name");
                return (new UsersAction().execute(request, response));
            }
            if (!GenericValidator.maxLength(userName, 15)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for User Name");
                return (new UsersAction().execute(request, response));
            }
            if (!GenericValidator.maxLength(realName, 50)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for Real Name");
                return (new UsersAction().execute(request, response));
            }
            if (!GenericValidator.maxLength(password, 50)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for Password");
                return (new UsersAction().execute(request, response));
            }

            if (!GenericValidator.minLength(password, 8)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid Password");
                return (new UsersAction().execute(request, response));
            }
            if (!GenericValidator.matchRegexp(password, HTTPConstants.PASSWORD_PATTERN_REGEXP)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid Password");
                return (new UsersAction().execute(request, response));
            }
            if (!GenericValidator.minLength(confirmPassword, 8)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid Password");
                return (new UsersAction().execute(request, response));
            }

            if (!GenericValidator.matchRegexp(confirmPassword, HTTPConstants.PASSWORD_PATTERN_REGEXP)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input for Password");
                return (new UsersAction().execute(request, response));
            }
            if (!password.equals(confirmPassword)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Password do not match");
                return (new UsersAction().execute(request, response));
            }
            if (!GenericValidator.isEmail(userEmail)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid Email ID");
                return (new UsersAction().execute(request, response));
            }
            if (!GenericValidator.maxLength(userEmail, 50)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for Email ID");
                return (new UsersAction().execute(request, response));
            }
            if (!GenericValidator.maxLength(userDescription, 50)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for User Description");
                return (new UsersAction().execute(request, response));
            }
            if (!User.USER_TYPE_ADMIN.equalsIgnoreCase(userType)) {
                userType = User.USER_TYPE_USER;
            }

            boolean userExist = UserDAO.getInstance().validateUser(userName);
            boolean emailExist = UserDAO.getInstance().validateUserEmail(userEmail);
            if (userExist) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "User with this username already exist");
                return (new UsersAction().execute(request, response));
            }
            if (emailExist) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "User with this email Id already exist");
                return (new UsersAction().execute(request, response));
            }

            User user = new User();
            user.setUserName(userName);
            user.setPassword(password);
            user.setUserDescription(userDescription);
            user.setUserEmail(userEmail);
            user.setRealName(realName);
            user.setActive(true);
            user.setUserType(userType);

            UserDAO.getInstance().addUser(user);

            user = UserDAO.getInstance().readUserByName(userName);

            PasswordHistory passwordHistory = new PasswordHistory();
            passwordHistory.setUserId(user.getUserId());
            passwordHistory.setPassword(password);
            PasswordHistoryDAO.getInstance().create(passwordHistory);

            AuditLogManager.log(new AuditLogRecord(user.getUserId(), AuditLogRecord.OBJECT_USER,
                    AuditLogRecord.ACTION_CREATED, loggedInUser.getUserName(), request.getRemoteAddr(),
                    AuditLogRecord.LEVEL_INFO, "ID :" + user.getUserId(), "Name : " + user.getUserName()));

            request.setAttribute(HTTPConstants.REQUEST_MESSAGE,
                    "User " + userName.toUpperCase() + " added successfully");
            return (new UsersAction().execute(request, response));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return (new NewUserView(request, response));
}

From source file:com.jd.survey.domain.survey.QuestionAnswerValidator.java

@Override
public void validate(Object obj, Errors errors) {
    try {/*from w w w .  ja v a2  s.  c  o m*/

        boolean isValid;
        String validationFieldName = "stringAnswerValue";
        QuestionAnswer questionAnswer = (QuestionAnswer) obj;
        Question question = questionAnswer.getQuestion();
        String valueToValidate;
        BigDecimalValidator bigDecimalValidator;
        int optionsCount;
        int rowCount;
        int columnCount;
        System.out.println("Question type: " + question.getType());
        if (question.getVisible()) {
            switch (question.getType()) {
            case YES_NO_DROPDOWN: //Yes No DropDown 
                break;
            case SHORT_TEXT_INPUT: //Short Text Input
                //validate isRequired
                valueToValidate = questionAnswer.getStringAnswerValue();
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }
                //continue validation if value entered is not null or empty
                if (valueToValidate != null && !valueToValidate.isEmpty()) {
                    //validate range
                    if (question.getIntegerMinimum() != null
                            && !GenericValidator.minLength(valueToValidate, question.getIntegerMinimum())) {
                        errors.rejectValue(validationFieldName, "field_length_min",
                                new Object[] { question.getIntegerMinimum() },
                                "The length of the text must exceed " + question.getIntegerMinimum());
                        break;
                    }
                    if (question.getIntegerMaximum() != null
                            && !GenericValidator.maxLength(valueToValidate, question.getIntegerMaximum())) {
                        errors.rejectValue(validationFieldName, "field_length_max",
                                new Object[] { question.getIntegerMaximum() },
                                "The length of the text must not exceed " + question.getIntegerMaximum());
                        break;
                    }

                    //validate regular expression 
                    if (question.getRegularExpression() != null
                            && !question.getRegularExpression().trim().isEmpty() && !GenericValidator
                                    .matchRegexp(valueToValidate, question.getRegularExpression())) {
                        errors.rejectValue(validationFieldName, "field_invalid_type", "Invalid entry");
                        break;
                    }
                }
                break;
            case LONG_TEXT_INPUT: //Long Text Input
                //validate isRequired
                valueToValidate = questionAnswer.getStringAnswerValue();
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }
                //continue validation if value entered is not null or empty
                if (valueToValidate != null && !valueToValidate.isEmpty()) {
                    //validate range
                    if (question.getIntegerMinimum() != null
                            && !GenericValidator.minLength(valueToValidate, question.getIntegerMinimum())) {
                        errors.rejectValue(validationFieldName, "field_length_min",
                                new Object[] { question.getIntegerMinimum() },
                                "The length of the text must exceed " + question.getIntegerMinimum());
                        break;
                    }
                    if (question.getIntegerMaximum() != null
                            && !GenericValidator.maxLength(valueToValidate, question.getIntegerMaximum())) {
                        errors.rejectValue(validationFieldName, "field_length_max",
                                new Object[] { question.getIntegerMaximum() },
                                "The length of the text must not exceed " + question.getIntegerMaximum());
                        break;
                    }
                    //validate regular expression 
                    if (question.getRegularExpression() != null
                            && !question.getRegularExpression().trim().isEmpty() && !GenericValidator
                                    .matchRegexp(valueToValidate, question.getRegularExpression())) {
                        errors.rejectValue(validationFieldName, "field_invalid_type", "Invalid entry");
                        break;
                    }
                }
                break;
            case HUGE_TEXT_INPUT: //Huge Text Input
                //validate isRequired
                valueToValidate = questionAnswer.getStringAnswerValue();
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }
                //continue validation if value entered is not null or empty
                if (valueToValidate != null && !valueToValidate.isEmpty()) {
                    //validate range   
                    if (question.getIntegerMinimum() != null
                            && !GenericValidator.minLength(valueToValidate, question.getIntegerMinimum())) {
                        errors.rejectValue(validationFieldName, "field_length_min",
                                new Object[] { question.getIntegerMinimum() },
                                "The length of the text must exceed " + question.getIntegerMinimum());
                        break;
                    }
                    if (question.getIntegerMaximum() != null
                            && !GenericValidator.maxLength(valueToValidate, question.getIntegerMaximum())) {
                        errors.rejectValue(validationFieldName, "field_length_max",
                                new Object[] { question.getIntegerMaximum() },
                                "The length of the text must not exceed " + question.getIntegerMaximum());
                        break;
                    }
                    //validate regular expression 
                    if (question.getRegularExpression() != null
                            && !question.getRegularExpression().trim().isEmpty() && !GenericValidator
                                    .matchRegexp(valueToValidate, question.getRegularExpression())) {
                        errors.rejectValue(validationFieldName, "field_invalid_type", "Invalid entry");
                        break;
                    }
                }
                break;
            case INTEGER_INPUT: //Integer Input
                valueToValidate = questionAnswer.getStringAnswerValue();
                //validate isRequired
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is invalid");
                    break;
                }
                //continue validation if value entered is not null or empty
                if (valueToValidate != null && !valueToValidate.isEmpty()) {
                    if (!GenericValidator.isInt(valueToValidate)) {
                        errors.rejectValue(validationFieldName, "field_invalid_integer",
                                "This field is invalid");
                        break;
                    }

                    //validate range
                    if (question.getIntegerMinimum() != null
                            && !GenericValidator.minValue((int) Integer.parseInt(valueToValidate),
                                    (int) question.getIntegerMinimum())) {

                        errors.rejectValue(validationFieldName, "field_value_min",
                                new Object[] { question.getIntegerMinimum() },
                                "The value of this field must exceed " + question.getIntegerMinimum());
                        break;
                    }
                    if (question.getIntegerMaximum() != null
                            && !GenericValidator.maxValue((int) Integer.parseInt(valueToValidate),
                                    (int) question.getIntegerMaximum())) {
                        errors.rejectValue(validationFieldName, "field_value_max",
                                new Object[] { question.getIntegerMaximum() },
                                "The value of this field must not exceed " + question.getIntegerMaximum());
                        break;
                    }
                }
                questionAnswer.setLongAnswerValue(valueToValidate != null && valueToValidate.length() > 0
                        ? Long.parseLong(valueToValidate)
                        : null);
                break;
            case CURRENCY_INPUT: //Currency Input
                valueToValidate = questionAnswer.getStringAnswerValue();
                //validate isRequired
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }

                //continue validation if value entered is not null or empty
                if (valueToValidate != null && !valueToValidate.isEmpty()) {

                    CurrencyValidator currencyValidator = new CurrencyValidator(true, true);
                    if (!currencyValidator.isValid(valueToValidate, LocaleContextHolder.getLocale())) {
                        errors.rejectValue(validationFieldName, "field_invalid_currency",
                                "Invalid Currency Entered");
                        break;
                    }

                    //removing all '$' and ',' from string prior to validating max and min
                    valueToValidate = valueToValidate.replaceAll("\\$", "");
                    valueToValidate = valueToValidate.replaceAll(",", "");

                    //validate range
                    if (question.getDecimalMinimum() != null
                            && !GenericValidator.minValue((double) Double.parseDouble(valueToValidate),
                                    question.getDecimalMinimum().doubleValue())) {
                        errors.rejectValue(validationFieldName, "field_value_min",
                                new Object[] { question.getDecimalMinimum() },
                                "The value of this field must exceed " + question.getDecimalMinimum());
                        break;
                    }
                    if (question.getDecimalMaximum() != null
                            && !GenericValidator.maxValue((double) Double.parseDouble(valueToValidate),
                                    question.getDecimalMaximum().doubleValue())) {
                        errors.rejectValue(validationFieldName, "field_value_max",
                                new Object[] { question.getDecimalMaximum() },
                                "The value of this field must not exceed " + question.getDecimalMaximum());
                        break;
                    }

                    questionAnswer.setBigDecimalAnswerValue(
                            currencyValidator.validate(valueToValidate, LocaleContextHolder.getLocale()));
                    questionAnswer.setStringAnswerValue(currencyValidator.format(
                            currencyValidator.validate(valueToValidate, LocaleContextHolder.getLocale()),
                            LocaleContextHolder.getLocale()));

                }
                break;

            case DECIMAL_INPUT: //Numeric Input (Decimal)
                valueToValidate = questionAnswer.getStringAnswerValue();
                //validate isRequired
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }
                //continue validation if value entered is not null or empty
                bigDecimalValidator = new BigDecimalValidator(true);
                if (valueToValidate != null && !valueToValidate.isEmpty()) {
                    if (!bigDecimalValidator.isValid(valueToValidate, LocaleContextHolder.getLocale())) {
                        errors.rejectValue(validationFieldName, "field_invalid_decimal",
                                "Invalid Decimal Entered");
                        break;
                    } else {
                        questionAnswer.setStringAnswerValue(bigDecimalValidator.format(
                                bigDecimalValidator.validate(valueToValidate, LocaleContextHolder.getLocale()),
                                LocaleContextHolder.getLocale()));
                    }

                    //removing all commas from string prior to validating max and min
                    valueToValidate = valueToValidate.replaceAll(",", "");
                    //validate range
                    if (question.getDecimalMinimum() != null
                            && !GenericValidator.minValue((double) Double.parseDouble(valueToValidate),
                                    question.getDecimalMinimum().doubleValue())) {
                        errors.rejectValue(validationFieldName, "field_value_min",
                                new Object[] { question.getDecimalMinimum() },
                                "The value of this field must exceed " + question.getDecimalMinimum());
                        break;
                    }
                    if (question.getDecimalMaximum() != null
                            && !GenericValidator.maxValue((double) Double.parseDouble(valueToValidate),
                                    question.getDecimalMaximum().doubleValue())) {
                        errors.rejectValue(validationFieldName, "field_value_max",
                                new Object[] { question.getDecimalMaximum() },
                                "The value of this field must not exceed " + question.getDecimalMaximum());
                        break;
                    }
                }
                questionAnswer.setBigDecimalAnswerValue(valueToValidate.trim().length() > 0
                        ? bigDecimalValidator.validate(valueToValidate, LocaleContextHolder.getLocale())
                        : null);
                break;
            case DATE_INPUT: //Date Input
                valueToValidate = questionAnswer.getStringAnswerValue();
                //validate isRequired   
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }

                //validate type if value entered is not null
                if (valueToValidate != null && !valueToValidate.isEmpty()) {
                    if (!GenericValidator.isDate(valueToValidate, dateFormat, true)) {
                        errors.rejectValue(validationFieldName, "field_invalid_date", "Invalid Date");
                        break;
                    }
                    if (question.getDateMinimum() != null && (DateValidator.getInstance()
                            .validate(valueToValidate).compareTo(question.getDateMinimum()) <= 0)) {
                        errors.rejectValue(validationFieldName, "field_date_min",
                                new Object[] { question.getDateMinimum() },
                                "The date entered must be after " + question.getDateMinimum());
                        break;
                    }
                    if (question.getDateMaximum() != null && (DateValidator.getInstance()
                            .validate(valueToValidate).compareTo(question.getDateMaximum()) >= 0)) {
                        errors.rejectValue(validationFieldName, "field_date_max",
                                new Object[] { question.getDateMaximum() },
                                "The date entered must be before " + question.getDateMaximum());
                        break;
                    }
                }

                questionAnswer.setDateAnswerValue(valueToValidate.trim().length() > 0
                        ? DateValidator.getInstance().validate(valueToValidate)
                        : null);
                break;
            case SINGLE_CHOICE_DROP_DOWN: //Single choice Drop Down
                valueToValidate = questionAnswer.getStringAnswerValue();
                isValid = false;
                //validate isRequired
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }
                //verify that the value exists in the options
                for (QuestionOption option : question.getOptions()) {
                    if (option.getValue().equalsIgnoreCase(valueToValidate)) {
                        isValid = true;
                        break;
                    }
                }
                if (!isValid && !GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_invalid_type", "Invalid Option");
                    break;
                }

                break;
            case MULTIPLE_CHOICE_CHECKBOXES: //Multiple Choice Checkboxes
                //validate isRequired
                isValid = false;
                optionsCount = questionAnswer.getQuestion().getOptions().size();
                if (question.getRequired()) {
                    for (int i = 0; i < questionAnswer.getIntegerAnswerValuesArray().length; i++) {
                        if (questionAnswer.getIntegerAnswerValuesArray()[i] != null
                                && questionAnswer.getIntegerAnswerValuesArray()[i] <= optionsCount) {
                            //one element was checked
                            isValid = true;
                            break;
                        }
                    }
                    if (!isValid) {
                        errors.rejectValue(validationFieldName, "field_required", "This field is required");
                        break;
                    }
                }

                isValid = true;
                //verify that the value exists in the options range
                for (int i = 0; i < questionAnswer.getIntegerAnswerValuesArray().length; i++) {
                    if (questionAnswer.getIntegerAnswerValuesArray()[i] != null
                            && questionAnswer.getIntegerAnswerValuesArray()[i] > optionsCount) {
                        //one element was checked
                        isValid = false;
                        break;
                    }
                }
                if (!isValid) {
                    errors.rejectValue(validationFieldName, "field_invalid_type", "Invalid Option");
                    break;
                }

                break;
            case DATASET_DROP_DOWN: //Dataset DropDown
                valueToValidate = questionAnswer.getStringAnswerValue();
                isValid = false;
                //validate isRequired
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }
                //verify that the value exists in the dataset

                for (DataSetItem dataSetItem : question.getDataSetItems()) {
                    if (dataSetItem.getValue().equalsIgnoreCase(valueToValidate)) {
                        isValid = true;
                        break;
                    }
                }
                if (!isValid && !GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_invalid_type", "Invalid Option");
                    break;
                }

                break;

            case SINGLE_CHOICE_RADIO_BUTTONS: //Single Choice Radio Buttons 
                isValid = false;
                valueToValidate = questionAnswer.getStringAnswerValue();
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }

                //verify that the value exists in the options
                for (QuestionOption option : question.getOptions()) {
                    if (option.getValue().equalsIgnoreCase(valueToValidate)) {
                        isValid = true;
                        break;
                    }
                }
                if (!isValid && !GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_invalid_type", "Invalid Option");
                    break;
                }

                break;

            case YES_NO_DROPDOWN_MATRIX://Yes No DropDown Matrix
                break;
            case SHORT_TEXT_INPUT_MATRIX://Short Text Input Matrix
                rowCount = questionAnswer.getQuestion().getRowLabels().size();
                columnCount = questionAnswer.getQuestion().getColumnLabels().size();
                for (int r = 1; r <= rowCount; r++) {
                    for (int c = 1; c <= columnCount; c++) {
                        valueToValidate = questionAnswer.getStringAnswerValuesMatrix()[r - 1][c - 1];
                        validationFieldName = "stringAnswerValuesMatrix[" + (r - 1) + "][" + (c - 1) + "]";
                        //validate isRequired
                        if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                            errors.rejectValue(validationFieldName, "field_required", "This field is required");
                            continue;
                        }
                        //continue validation if value entered is not null or empty
                        if (valueToValidate != null && !valueToValidate.isEmpty()) {
                            //validate range
                            if (question.getIntegerMinimum() != null && !GenericValidator
                                    .minLength(valueToValidate, question.getIntegerMinimum())) {
                                errors.rejectValue(validationFieldName, "field_length_min",
                                        new Object[] { question.getIntegerMinimum() },
                                        "The length of the text must exceed " + question.getIntegerMinimum());
                                continue;
                            }
                            if (question.getIntegerMaximum() != null && !GenericValidator
                                    .maxLength(valueToValidate, question.getIntegerMaximum())) {
                                errors.rejectValue(validationFieldName, "field_length_max",
                                        new Object[] { question.getIntegerMaximum() },
                                        "The length of the text must not exceed "
                                                + question.getIntegerMaximum());
                                continue;
                            }

                            //validate regular expression 
                            if (question.getRegularExpression() != null
                                    && !question.getRegularExpression().trim().isEmpty() && !GenericValidator
                                            .matchRegexp(valueToValidate, question.getRegularExpression())) {
                                errors.rejectValue(validationFieldName, "field_invalid_type", "Invalid entry");
                                continue;
                            }
                        }
                    }
                }
                break;
            case INTEGER_INPUT_MATRIX://Integer Input Matrix
                rowCount = questionAnswer.getQuestion().getRowLabels().size();
                columnCount = questionAnswer.getQuestion().getColumnLabels().size();
                for (int r = 1; r <= rowCount; r++) {
                    for (int c = 1; c <= columnCount; c++) {
                        valueToValidate = questionAnswer.getStringAnswerValuesMatrix()[r - 1][c - 1];
                        validationFieldName = "stringAnswerValuesMatrix[" + (r - 1) + "][" + (c - 1) + "]";

                        //validate isRequired
                        if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                            errors.rejectValue(validationFieldName, "field_required", "This field is invalid");
                            continue;
                        }

                        //continue validation if value entered is not null or empty
                        if (valueToValidate != null && !valueToValidate.isEmpty()) {
                            if (!GenericValidator.isInt(valueToValidate)) {
                                errors.rejectValue(validationFieldName, "field_invalid_integer",
                                        "This field is invalid");
                                continue;
                            }

                            //validate range
                            if (question.getIntegerMinimum() != null
                                    && !GenericValidator.minValue((int) Integer.parseInt(valueToValidate),
                                            (int) question.getIntegerMinimum())) {
                                errors.rejectValue(validationFieldName, "field_value_min",
                                        new Object[] { question.getIntegerMinimum() },
                                        "The value of this field must exceed " + question.getIntegerMinimum());
                                continue;
                            }
                            if (question.getIntegerMaximum() != null
                                    && !GenericValidator.maxValue((int) Integer.parseInt(valueToValidate),
                                            (int) question.getIntegerMaximum())) {
                                errors.rejectValue(validationFieldName, "field_value_max",
                                        new Object[] { question.getIntegerMaximum() },
                                        "The value of this field must not exceed "
                                                + question.getIntegerMaximum());
                                continue;
                            }
                        }
                        questionAnswer.getLongAnswerValuesMatrix()[r - 1][c - 1] = (valueToValidate != null
                                && valueToValidate.length() > 0 ? Long.parseLong(valueToValidate) : null);
                    }
                }
                break;
            case CURRENCY_INPUT_MATRIX://Currency Input Matrix  NEED TO ADD MAX MIN???????????????????????????????????????????????????
                rowCount = questionAnswer.getQuestion().getRowLabels().size();
                columnCount = questionAnswer.getQuestion().getColumnLabels().size();
                for (int r = 1; r <= rowCount; r++) {
                    for (int c = 1; c <= columnCount; c++) {
                        System.out.println("ROW: " + r + " / COL: " + c
                                + " -----------------------------------------------------------------------------------------");
                        valueToValidate = questionAnswer.getStringAnswerValuesMatrix()[r - 1][c - 1];
                        validationFieldName = "stringAnswerValuesMatrix[" + (r - 1) + "][" + (c - 1) + "]";
                        //validate isRequired
                        if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                            errors.rejectValue(validationFieldName, "field_required", "This field is required");
                            continue;
                        }

                        //continue validation if value entered is not null or empty
                        if (valueToValidate != null && !valueToValidate.isEmpty()) {
                            CurrencyValidator currencyValidator = new CurrencyValidator(true, true);
                            if (!currencyValidator.isValid(valueToValidate, LocaleContextHolder.getLocale())) {
                                errors.rejectValue(validationFieldName, "field_invalid_type",
                                        "Invalid Currency Entered");
                                continue;
                            } else {
                                questionAnswer.getBigDecimalAnswerValuesMatrix()[r - 1][c
                                        - 1] = currencyValidator.validate(valueToValidate,
                                                LocaleContextHolder.getLocale());
                                questionAnswer.getStringAnswerValuesMatrix()[r - 1][c - 1] = currencyValidator
                                        .format(currencyValidator.validate(valueToValidate,
                                                LocaleContextHolder.getLocale()),
                                                LocaleContextHolder.getLocale());
                            }
                            //removing all '$' and ',' from string prior to validating max and min
                            valueToValidate = valueToValidate.replaceAll("\\$", "");
                            valueToValidate = valueToValidate.replaceAll(",", "");

                            //Validating max and min
                            if (question.getDecimalMinimum() == null) {
                                System.out.println(
                                        "MIN IS NULL!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                            }
                            if (question.getDecimalMinimum() != null
                                    && !GenericValidator.minValue((double) Double.parseDouble(valueToValidate),
                                            question.getDecimalMinimum().doubleValue())) {
                                System.out.println(validationFieldName
                                        + "MIN ##################################################################################");
                                errors.rejectValue(validationFieldName, "field_value_min",
                                        new Object[] { question.getDecimalMinimum() },
                                        "The value of this field must exceed " + question.getDecimalMinimum());
                                continue;
                            }
                            if (question.getDecimalMaximum() == null) {
                                System.out.println(
                                        "MAX IS NULL!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                            }

                            if (question.getDecimalMaximum() != null
                                    && !GenericValidator.maxValue((double) Double.parseDouble(valueToValidate),
                                            question.getDecimalMaximum().doubleValue())) {
                                System.out.println(validationFieldName
                                        + "MAX ########################################################################################################");
                                errors.rejectValue(validationFieldName, "field_value_max",
                                        new Object[] { question.getDecimalMaximum() },
                                        "The value of this field must not exceed "
                                                + question.getDecimalMaximum());
                                continue;
                            }
                        }
                    }
                }
                break;

            case DECIMAL_INPUT_MATRIX://Decimal Input Matrix
                rowCount = questionAnswer.getQuestion().getRowLabels().size();
                columnCount = questionAnswer.getQuestion().getColumnLabels().size();
                for (int r = 1; r <= rowCount; r++) {
                    for (int c = 1; c <= columnCount; c++) {
                        valueToValidate = questionAnswer.getStringAnswerValuesMatrix()[r - 1][c - 1];
                        validationFieldName = "stringAnswerValuesMatrix[" + (r - 1) + "][" + (c - 1) + "]";
                        //validate isRequired
                        if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                            errors.rejectValue(validationFieldName, "field_required", "This field is required");
                            continue;
                        }

                        //continue validation if value entered is not null or empty
                        bigDecimalValidator = new BigDecimalValidator(true);
                        if (valueToValidate != null && !valueToValidate.isEmpty()) {
                            if (!bigDecimalValidator.isValid(valueToValidate,
                                    LocaleContextHolder.getLocale())) {
                                errors.rejectValue(validationFieldName, "field_invalid_type",
                                        "Invalid Decimal Entered");
                                continue;
                            } else {
                                questionAnswer.setStringAnswerValue(bigDecimalValidator.format(
                                        bigDecimalValidator.validate(valueToValidate,
                                                LocaleContextHolder.getLocale()),
                                        LocaleContextHolder.getLocale()));
                            }

                            //validate range
                            if (question.getDecimalMinimum() != null
                                    && !GenericValidator.minValue((double) Double.parseDouble(valueToValidate),
                                            question.getDecimalMinimum().doubleValue())) {
                                errors.rejectValue(validationFieldName, "field_value_min",
                                        new Object[] { question.getDecimalMinimum() },
                                        "The value of this field must exceed " + question.getDecimalMinimum());
                                continue;
                            }
                            if (question.getDecimalMaximum() != null
                                    && !GenericValidator.maxValue((double) Double.parseDouble(valueToValidate),
                                            question.getDecimalMaximum().doubleValue())) {
                                errors.rejectValue(validationFieldName, "field_value_max",
                                        new Object[] { question.getDecimalMaximum() },
                                        "The value of this field must not exceed "
                                                + question.getDecimalMaximum());
                                continue;
                            }
                        }
                        questionAnswer.getBigDecimalAnswerValuesMatrix()[r - 1][c
                                - 1] = (valueToValidate.trim().length() > 0 ? bigDecimalValidator
                                        .validate(valueToValidate, LocaleContextHolder.getLocale()) : null);

                    }
                }
                break;
            case DATE_INPUT_MATRIX://Date Input Matrix
                rowCount = questionAnswer.getQuestion().getRowLabels().size();
                columnCount = questionAnswer.getQuestion().getColumnLabels().size();
                for (int r = 1; r <= rowCount; r++) {
                    for (int c = 1; c <= columnCount; c++) {
                        valueToValidate = questionAnswer.getStringAnswerValuesMatrix()[r - 1][c - 1];
                        validationFieldName = "stringAnswerValuesMatrix[" + (r - 1) + "][" + (c - 1) + "]";

                        //validate isRequired   
                        if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                            errors.rejectValue(validationFieldName, "field_required", "This field is required");
                            continue;
                        }

                        //validate type if value entered is not null
                        if (valueToValidate != null && !valueToValidate.isEmpty()) {
                            if (!GenericValidator.isDate(valueToValidate, dateFormat, true)) {
                                errors.rejectValue(validationFieldName, "field_invalid_date", "Invalid Date");
                                continue;
                            }
                            if (question.getDateMinimum() != null && (DateValidator.getInstance()
                                    .validate(valueToValidate).compareTo(question.getDateMinimum()) <= 0)) {
                                errors.rejectValue(validationFieldName, "field_date_min",
                                        new Object[] { question.getDateMinimum() },
                                        "The date entered must be after " + question.getDateMinimum());
                                continue;
                            }
                            if (question.getDateMaximum() != null && (DateValidator.getInstance()
                                    .validate(valueToValidate).compareTo(question.getDateMaximum()) >= 0)) {
                                errors.rejectValue(validationFieldName, "field_date_max",
                                        new Object[] { question.getDateMaximum() },
                                        "The date entered must be before " + question.getDateMaximum());
                                continue;
                            }
                        }
                        questionAnswer.getDateAnswerValuesMatrix()[r - 1][c
                                - 1] = (valueToValidate.trim().length() > 0
                                        ? DateValidator.getInstance().validate(valueToValidate)
                                        : null);
                    }
                }
                break;
            case STAR_RATING:
                valueToValidate = questionAnswer.getStringAnswerValue();
                //validate isRequired
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }
                break;
            case SMILEY_FACES_RATING:
                valueToValidate = questionAnswer.getStringAnswerValue();
                //validate isRequired
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }
                break;

            case IMAGE_DISPLAY:
                //no validation
                break;
            case VIDEO_DISPLAY:
                //no validation
                break;
            case FILE_UPLOAD:
                //validate that the file is not null
                if (question.getRequired() && (questionAnswer.getSurveyDocument() == null)
                        && !questionAnswer.getDocumentAlreadyUploded()) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }

                //check the file type from the file extension    
                if (questionAnswer.getSurveyDocument() != null
                        && !validateFileType(questionAnswer.getSurveyDocument().getContentType())) {
                    errors.rejectValue(validationFieldName, invalidContentMessage, this.invalidContentMessage);
                    break;
                }

                //validate the size
                if (questionAnswer.getSurveyDocument() != null
                        && !((questionAnswer.getSurveyDocument().getContent().length) <= maximunFileSize
                                * ONE_BYTE)) {
                    errors.rejectValue(validationFieldName, invalidFileSizeMessage,
                            this.invalidFileSizeMessage);
                    break;
                }

                break;

            }

        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:jp.co.ctc_g.jse.core.validation.util.Validators.java

/**
 * ?????????????????????/*from   w w w. j  a  va 2 s . c  om*/
 * ??{@link GenericValidator#minLength(String, int)}?????
 * @param suspect 
 * @param size 
 * @return GenericValidator#minLength(String, int)??
 */
public static boolean minLength(CharSequence suspect, int size) {
    return GenericValidator.minLength(suspect.toString(), size);
}

From source file:it.eng.spagobi.commons.validation.SpagoBIValidationImpl.java

public static EMFValidationError validateField(String fieldName, String fieldLabel, String value,
        String validatorName, String arg0, String arg1, String arg2) throws Exception {

    List params = null;//from   w ww  .  j  av a  2  s.  c  o  m

    if (validatorName.equalsIgnoreCase("MANDATORY")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the MANDATORY VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        if (GenericValidator.isBlankOrNull(value)) {
            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_MANDATORY, params);

        }

    } else if (validatorName.equalsIgnoreCase("URL")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the URL VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        UrlValidator urlValidator = new SpagoURLValidator();
        if (!GenericValidator.isBlankOrNull(value) && !urlValidator.isValid(value)) {
            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_URL, params);

        }
    } else if (validatorName.equalsIgnoreCase("LETTERSTRING")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the LETTERSTRING VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        if (!GenericValidator.isBlankOrNull(value)
                && !GenericValidator.matchRegexp(value, LETTER_STRING_REGEXP)) {
            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_LETTERSTRING, params);

        }
    } else if (validatorName.equalsIgnoreCase("ALFANUMERIC")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the ALFANUMERIC VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        if (!GenericValidator.isBlankOrNull(value)
                && !GenericValidator.matchRegexp(value, ALPHANUMERIC_STRING_REGEXP)) {

            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_ALFANUMERIC, params);

        }
    } else if (validatorName.equalsIgnoreCase("NUMERIC")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the NUMERIC VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        if (!GenericValidator.isBlankOrNull(value) && (!(GenericValidator.isInt(value)
                || GenericValidator.isFloat(value) || GenericValidator.isDouble(value)
                || GenericValidator.isShort(value) || GenericValidator.isLong(value)))) {

            // The string is not a integer, not a float, not double, not short, not long
            // so is not a number

            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_NUMERIC, params);

        }

    } else if (validatorName.equalsIgnoreCase("EMAIL")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the EMAIL VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        if (!GenericValidator.isBlankOrNull(value) && !GenericValidator.isEmail(value)) {

            // Generate errors
            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_EMAIL, params);

        }
    } else if (validatorName.equalsIgnoreCase("BOOLEAN")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the MANDATORY VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        if (!GenericValidator.isBlankOrNull(value) && !value.equalsIgnoreCase("true")
                && !value.equalsIgnoreCase("false")) {
            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_BOOLEAN, params);

        }

    } else if (validatorName.equalsIgnoreCase("FISCALCODE")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the FISCALCODE VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        if (!GenericValidator.isBlankOrNull(value)
                && !GenericValidator.matchRegexp(value, FISCAL_CODE_REGEXP)) {

            //             Generate errors
            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_FISCALCODE, params);

        }
    } else if (validatorName.equalsIgnoreCase("DECIMALS")) {
        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the DECIMALS VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            int maxNumberOfDecimalDigit = Integer.valueOf(arg0).intValue();
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Max Numbers of decimals is [" + maxNumberOfDecimalDigit + "]");
            String decimalSeparator = arg1;

            if (GenericValidator.isBlankOrNull(decimalSeparator)) {
                decimalSeparator = ".";
            }

            int pos = value.indexOf(decimalSeparator);
            String decimalCharacters = "";
            if (pos != -1)
                decimalCharacters = value.substring(pos + 1);

            if (decimalCharacters.length() > maxNumberOfDecimalDigit) {
                // Generate errors
                params = new ArrayList();
                params.add(fieldLabel);
                params.add(String.valueOf(maxNumberOfDecimalDigit));
                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_DECIMALS, params);
            }
        }
    } else if (validatorName.equalsIgnoreCase("NUMERICRANGE")) {
        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the NUMERICRANGE VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            String firstValueStr = arg0;
            String secondValueStr = arg1;
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Range is [" + firstValueStr + "< x <" + secondValueStr + "]");
            boolean syntaxCorrect = true;
            if (!GenericValidator.isDouble(value)) {
                SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                        " CANNOT APPLY THE NUMERICRANGE VALIDATOR  value [" + value + "] is not a Number");
                syntaxCorrect = false;
            }
            if (!GenericValidator.isDouble(firstValueStr)) {
                SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                        " CANNOT APPLY THE NUMERICRANGE VALIDATOR  first value of range [" + firstValueStr
                                + "] is not a Number");
                syntaxCorrect = false;
            }
            if (!GenericValidator.isDouble(secondValueStr)) {
                SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                        " CANNOT APPLY THE NUMERICRANGE VALIDATOR  second value of range [" + secondValueStr
                                + "] is not a Number");
                syntaxCorrect = false;
            }
            if (syntaxCorrect) {
                double firstValue = Double.valueOf(firstValueStr).doubleValue();
                double secondValue = Double.valueOf(secondValueStr).doubleValue();
                double valueToCheckDouble = Double.valueOf(value).doubleValue();
                if (!(GenericValidator.isInRange(valueToCheckDouble, firstValue, secondValue))) {

                    params = new ArrayList();
                    params.add(fieldLabel);
                    params.add(firstValueStr);
                    params.add(secondValueStr);
                    return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_RANGE, params);

                }
            } else {
                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_GENERIC);
            }
        }
    } else if (validatorName.equalsIgnoreCase("DATERANGE")) {

        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the DATERANGE VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            String firstValueStr = arg0;
            String secondValueStr = arg1;
            String dateFormat = arg2;
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Range is [" + firstValueStr + "< x <" + secondValueStr + "]");
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Date Format is  [" + dateFormat + "]");
            //         //boolean syntaxCorrect = false;
            boolean syntaxCorrect = true;

            //if (!GenericValidator.isDate(value,dateFormat,true)){
            if (!GenericValidator.isDate(value, dateFormat, true)) {
                SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                        " CANNOT APPLY THE DATERANGE VALIDATOR  value [" + value
                                + "] is not a is not valid Date according to [" + dateFormat + "]");
                syntaxCorrect = false;
            }
            //if (!GenericValidator.isDate(firstValueStr,dateFormat,true)){
            if (!GenericValidator.isDate(firstValueStr, dateFormat, true)) {
                SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                        " CANNOT APPLY THE DATERANGE VALIDATOR  first value of range [" + firstValueStr
                                + "] is not valid Date according to [" + dateFormat + "]");
                syntaxCorrect = false;
            }
            //if (!GenericValidator.isDate(secondValueStr,dateFormat, true)){
            if (!GenericValidator.isDate(secondValueStr, dateFormat, true)) {
                SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                        " CANNOT APPLY THE DATERANGE VALIDATOR  second value of range [" + secondValueStr
                                + "] is not a valid Date according to [" + dateFormat + "]");
                syntaxCorrect = false;
            }

            if (syntaxCorrect) {
                DateFormat df = new SimpleDateFormat(dateFormat);

                Date firstValueDate = df.parse(firstValueStr);
                Date secondValueDate = df.parse(secondValueStr);
                Date theValueDate = df.parse(value);

                if ((theValueDate.getTime() < firstValueDate.getTime())
                        || (theValueDate.getTime() > secondValueDate.getTime())) {
                    params = new ArrayList();
                    params.add(fieldLabel);
                    params.add(firstValueStr);
                    params.add(secondValueStr);
                    return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_RANGE, params);
                }
            } else {
                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_GENERIC);
            }
        }
    } else if (validatorName.equalsIgnoreCase("STRINGRANGE")) {
        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the STRINGRANGE VALIDATOR to field [" + fieldName + "] with value [" + value + "]");

            String firstValueStr = arg0;
            String secondValueStr = arg1;
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Range is [" + firstValueStr + "< x <" + secondValueStr + "]");
            //if (firstValueStr.compareTo(secondValueStr) > 0){
            if ((value.compareTo(firstValueStr) < 0) || (value.compareTo(secondValueStr) > 0)) {
                params = new ArrayList();
                params.add(fieldLabel);
                params.add(firstValueStr);
                params.add(secondValueStr);
                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_RANGE, params);
            }
        }
    } else if (validatorName.equalsIgnoreCase("MAXLENGTH")) {
        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the MAXLENGTH VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            int maxLength = Integer.valueOf(arg0).intValue();
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "maxLength is [" + maxLength + "]");
            if (!GenericValidator.maxLength(value, maxLength)) {

                params = new ArrayList();
                params.add(fieldLabel);
                params.add(String.valueOf(maxLength));

                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_MAXLENGTH, params);

            }
        }
    } else if (validatorName.equalsIgnoreCase("MINLENGTH")) {
        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the MINLENGTH VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            int minLength = Integer.valueOf(arg0).intValue();
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "minLength is [" + minLength + "]");
            if (!GenericValidator.minLength(value, minLength)) {

                // Generate Errors
                params = new ArrayList();
                params.add(fieldLabel);
                params.add(String.valueOf(minLength));

                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_MINLENGTH, params);

            }
        }
    } else if (validatorName.equalsIgnoreCase("REGEXP")) {
        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the REGEXP VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            String regexp = arg0;
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator", "regexp is [" + regexp + "]");
            if (!(GenericValidator.matchRegexp(value, regexp))) {

                // Generate Errors
                params = new ArrayList();
                params.add(fieldLabel);
                params.add(regexp);

                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_REGEXP, params);

            }
        }
    } else if (validatorName.equalsIgnoreCase("XSS")) {
        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the XSS VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            String toVerify = value.toUpperCase();
            if (toVerify.contains("<A") || toVerify.contains("<LINK") || toVerify.contains("<IMG")
                    || toVerify.contains("<SCRIPT") || toVerify.contains("&LT;A")
                    || toVerify.contains("&LT;LINK") || toVerify.contains("&LT;IMG")
                    || toVerify.contains("&LT;SCRIPT")) {

                // Generate Errors
                params = new ArrayList();
                params.add(fieldLabel);

                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_XSS, params);

            }
        }
    } else if (validatorName.equalsIgnoreCase("DATE")) {

        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the DATE VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            String dateFormat = arg0;
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "dateFormat is [" + dateFormat + "]");
            //if (!GenericValidator.isDate(value, dateFormat, true)){
            if (!GenericValidator.isDate(value, dateFormat, true)) {

                //Generate Errors
                params = new ArrayList();
                params.add(fieldLabel);
                params.add(dateFormat);

                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_DATE, params);
            }
        }

    }

    // all checks had positive result (no errors)
    return null;
}

From source file:com.sapienter.jbilling.common.GatewayBL.java

private boolean vSize(String parameter, int min, int max) {
    boolean retValue;
    String field = getStringPar(parameter, true);
    if (field == null) {
        retValue = false;/* w  ww. ja v a2 s .c o m*/
    } else {
        retValue = GenericValidator.minLength(field, min) && GenericValidator.maxLength(field, max);
        if (!retValue) {
            code = RES_CODE_ERROR;
            subCode = RES_SUB_CODE_ERR_LENGTH;
            text = " [" + parameter + "]" + MSG_BAD_LENGTH + min + " and " + max;
        }
    }

    return retValue;
}

From source file:it.eng.spagobi.commons.utilities.BIObjectValidator.java

/**
 * For each input field type (Numeric, URL, extc:), this method applies validation.
 * Every time a validation fails, an error is added to the <code>errorHandler</code>
 * errors stack.//from   w  w w .  jav  a  2 s  .c  om
 * The field label to be displayed is defined in file validation.xml for each 
 * validation: if it is not defined it is set with the field name; if it starts with 
 * "#" it is interpreted as a key and the message is recovered by 
 * PortletUtilities.getMessage(key, "messages") method, else it remains unchanged. 
 * 
 * @param serviceRequest The request Source Bean
 * @param errorHandler The errors Stack 
 * @throws Exception If any exception occurs.
 */
private void automaticValidation(SourceBean serviceRequest, EMFErrorHandler errorHandler) throws Exception {

    // Reperisco l'elenco di tutti gli attributi che mi aspetto di trovare
    // nella richiesta
    List fields = _validationStructure.getAttributeAsList("FIELDS.FIELD");

    for (Iterator iter = fields.iterator(); iter.hasNext();) {

        String value = null;

        List validators = null;
        SourceBean currentValidator = null;
        String validatorName = null;
        Iterator itValidators = null;
        try {
            SourceBean field = (SourceBean) iter.next();

            String fieldName = (String) field.getAttribute("name");

            value = (String) serviceRequest.getAttribute(fieldName);

            //********************************************
            String fieldLabel = (String) field.getAttribute("label");
            if (fieldLabel != null && fieldLabel.startsWith("#")) {
                String key = fieldLabel.substring(1);
                String fieldDescription = PortletUtilities.getMessage(key, "messages");
                if (fieldDescription != null && !fieldDescription.trim().equals(""))
                    fieldLabel = fieldDescription;
            }
            if (fieldLabel == null || fieldLabel.trim().equals(""))
                fieldLabel = fieldName;
            //********************************************

            validators = field.getAttributeAsList("VALIDATOR");

            itValidators = validators.iterator();

            Vector params = new Vector();
            while (itValidators.hasNext()) {
                currentValidator = (SourceBean) itValidators.next();
                validatorName = (String) currentValidator.getAttribute("validatorName");

                if (validatorName.equalsIgnoreCase("MANDATORY")) {
                    SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                            "Apply the MANDATORY VALIDATOR to field [" + field + "] with value [" + value
                                    + "]");
                    if (GenericValidator.isBlankOrNull(value)) {
                        params = new Vector();
                        params.add(fieldLabel);
                        errorHandler
                                .addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_MANDATORY, params));

                    }

                } else if (validatorName.equalsIgnoreCase("URL")) {
                    SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                            "Apply the URL VALIDATOR to field [" + field + "] with value [" + value + "]");
                    UrlValidator urlValidator = new SpagoURLValidator();
                    if (!GenericValidator.isBlankOrNull(value) && !urlValidator.isValid(value)) {
                        params = new Vector();
                        params.add(fieldLabel);
                        errorHandler.addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_URL, params));

                    }
                } else if (validatorName.equalsIgnoreCase("LETTERSTRING")) {
                    SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                            "Apply the LETTERSTRING VALIDATOR to field [" + field + "] with value [" + value
                                    + "]");
                    if (!GenericValidator.isBlankOrNull(value)
                            && !GenericValidator.matchRegexp(value, LETTER_STRING_REGEXP)) {
                        params = new Vector();
                        params.add(fieldLabel);
                        errorHandler
                                .addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_LETTERSTRING, params));

                    }
                } else if (validatorName.equalsIgnoreCase("ALFANUMERIC")) {
                    SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                            "Apply the ALFANUMERIC VALIDATOR to field [" + field + "] with value [" + value
                                    + "]");
                    if (!GenericValidator.isBlankOrNull(value)
                            && !GenericValidator.matchRegexp(value, ALPHANUMERIC_STRING_REGEXP)) {

                        params = new Vector();
                        params.add(fieldLabel);
                        errorHandler
                                .addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_ALFANUMERIC, params));

                    }
                } else if (validatorName.equalsIgnoreCase("NUMERIC")) {
                    SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                            "Apply the NUMERIC VALIDATOR to field [" + field + "] with value [" + value + "]");
                    if (!GenericValidator.isBlankOrNull(value) && (!(GenericValidator.isInt(value)
                            || GenericValidator.isFloat(value) || GenericValidator.isDouble(value)
                            || GenericValidator.isShort(value) || GenericValidator.isLong(value)))) {

                        // The string is not a integer, not a float, not double, not short, not long
                        // so is not a number

                        params = new Vector();
                        params.add(fieldLabel);
                        errorHandler.addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_NUMERIC, params));

                    }

                } else if (validatorName.equalsIgnoreCase("EMAIL")) {
                    SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                            "Apply the EMAIL VALIDATOR to field [" + field + "] with value [" + value + "]");
                    if (!GenericValidator.isBlankOrNull(value) && !GenericValidator.isEmail(value)) {

                        // Generate errors
                        params = new Vector();
                        params.add(fieldLabel);
                        errorHandler.addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_EMAIL, params));

                    }
                } else if (validatorName.equalsIgnoreCase("FISCALCODE")) {
                    SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                            "Apply the FISCALCODE VALIDATOR to field [" + field + "] with value [" + value
                                    + "]");
                    if (!GenericValidator.isBlankOrNull(value)
                            && !GenericValidator.matchRegexp(value, FISCAL_CODE_REGEXP)) {

                        //                      Generate errors
                        params = new Vector();
                        params.add(fieldLabel);
                        errorHandler
                                .addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_FISCALCODE, params));

                    }
                } else if (validatorName.equalsIgnoreCase("DECIMALS")) {
                    if (!GenericValidator.isBlankOrNull(value)) {
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Apply the DECIMALS VALIDATOR to field [" + field + "] with value [" + value
                                        + "]");
                        int maxNumberOfDecimalDigit = Integer
                                .valueOf((String) currentValidator.getAttribute("arg0")).intValue();
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Max Numbers of decimals is [" + maxNumberOfDecimalDigit + "]");
                        String decimalSeparator = (String) currentValidator.getAttribute("arg1");

                        if (GenericValidator.isBlankOrNull(decimalSeparator)) {
                            decimalSeparator = ".";
                        }

                        int pos = value.indexOf(decimalSeparator);
                        String decimalCharacters = "";
                        if (pos != -1)
                            decimalCharacters = value.substring(pos + 1);

                        if (decimalCharacters.length() > maxNumberOfDecimalDigit) {
                            // Generate errors
                            params = new Vector();
                            params.add(fieldLabel);
                            params.add(String.valueOf(maxNumberOfDecimalDigit));
                            errorHandler
                                    .addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_DECIMALS, params));
                        }
                    }
                } else if (validatorName.equalsIgnoreCase("NUMERICRANGE")) {
                    if (!GenericValidator.isBlankOrNull(value)) {
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Apply the NUMERICRANGE VALIDATOR to field [" + field + "] with value [" + value
                                        + "]");
                        String firstValueStr = (String) currentValidator.getAttribute("arg0");
                        String secondValueStr = (String) currentValidator.getAttribute("arg1");
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Range is [" + firstValueStr + "< x <" + secondValueStr + "]");
                        boolean syntaxCorrect = true;
                        if (!GenericValidator.isDouble(value)) {
                            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                    " CANNOT APPLY THE NUMERICRANGE VALIDATOR  value [" + value
                                            + "] is not a Number");
                            syntaxCorrect = false;
                        }
                        if (!GenericValidator.isDouble(firstValueStr)) {
                            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                    " CANNOT APPLY THE NUMERICRANGE VALIDATOR  first value of range ["
                                            + firstValueStr + "] is not a Number");
                            syntaxCorrect = false;
                        }
                        if (!GenericValidator.isDouble(secondValueStr)) {
                            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                    " CANNOT APPLY THE NUMERICRANGE VALIDATOR  second value of range ["
                                            + secondValueStr + "] is not a Number");
                            syntaxCorrect = false;
                        }
                        if (syntaxCorrect) {
                            double firstValue = Double.valueOf(firstValueStr).doubleValue();
                            double secondValue = Double.valueOf(secondValueStr).doubleValue();
                            double valueToCheckDouble = Double.valueOf(value).doubleValue();
                            if (!(GenericValidator.isInRange(valueToCheckDouble, firstValue, secondValue))) {

                                params = new Vector();
                                params.add(fieldLabel);
                                params.add(firstValueStr);
                                params.add(secondValueStr);
                                errorHandler.addError(
                                        new EMFUserError(EMFErrorSeverity.ERROR, ERROR_RANGE, params));

                            }
                        } else {
                            errorHandler.addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_GENERIC));
                        }
                    }
                } else if (validatorName.equalsIgnoreCase("DATERANGE")) {
                    if (!GenericValidator.isBlankOrNull(value)) {
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Apply the DATERANGE VALIDATOR to field [" + field + "] with value [" + value
                                        + "]");
                        String firstValueStr = (String) currentValidator.getAttribute("arg0");
                        String secondValueStr = (String) currentValidator.getAttribute("arg1");
                        String dateFormat = (String) currentValidator.getAttribute("arg2");
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Range is [" + firstValueStr + "< x <" + secondValueStr + "]");
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Date Format is  [" + dateFormat + "]");
                        boolean syntaxCorrect = false;

                        if (!GenericValidator.isDate(value, dateFormat, true)) {
                            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                    " CANNOT APPLY THE DATERANGE VALIDATOR  value [" + value
                                            + "] is not a is not valid Date according to [" + dateFormat + "]");
                            syntaxCorrect = false;
                        }
                        if (!GenericValidator.isDate(firstValueStr, dateFormat, true)) {
                            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                    " CANNOT APPLY THE DATERANGE VALIDATOR  first value of range ["
                                            + firstValueStr + "] is not valid Date according to [" + dateFormat
                                            + "]");
                            syntaxCorrect = false;
                        }
                        if (!GenericValidator.isDate(secondValueStr, dateFormat, true)) {
                            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                    " CANNOT APPLY THE DATERANGE VALIDATOR  second value of range ["
                                            + secondValueStr + "] is not a valid Date according to ["
                                            + dateFormat + "]");
                            syntaxCorrect = false;
                        }

                        if (syntaxCorrect) {
                            DateFormat df = new SimpleDateFormat(dateFormat);

                            Date firstValueDate = df.parse(firstValueStr);
                            Date secondValueDate = df.parse(secondValueStr);
                            Date theValueDate = df.parse(value);

                            if ((theValueDate.getTime() < firstValueDate.getTime())
                                    || (theValueDate.getTime() > secondValueDate.getTime())) {
                                params = new Vector();
                                params.add(fieldLabel);
                                params.add(firstValueStr);
                                params.add(secondValueStr);
                                errorHandler.addError(
                                        new EMFUserError(EMFErrorSeverity.ERROR, ERROR_RANGE, params));
                            }
                        } else {
                            errorHandler.addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_GENERIC));
                        }
                    }

                } else if (validatorName.equalsIgnoreCase("STRINGRANGE")) {
                    if (!GenericValidator.isBlankOrNull(value)) {
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Apply the STRINGRANGE VALIDATOR to field [" + field + "] with value [" + value
                                        + "]");

                        String firstValueStr = (String) currentValidator.getAttribute("arg0");
                        String secondValueStr = (String) currentValidator.getAttribute("arg1");
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Range is [" + firstValueStr + "< x <" + secondValueStr + "]");

                        if (firstValueStr.compareTo(secondValueStr) > 0) {
                            params = new Vector();
                            params.add(fieldLabel);
                            params.add(firstValueStr);
                            params.add(secondValueStr);
                            errorHandler
                                    .addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_RANGE, params));
                        }
                    }
                } else if (validatorName.equalsIgnoreCase("MAXLENGTH")) {
                    if (!GenericValidator.isBlankOrNull(value)) {
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Apply the MAXLENGTH VALIDATOR to field [" + field + "] with value [" + value
                                        + "]");
                        int maxLength = Integer.valueOf((String) currentValidator.getAttribute("arg0"))
                                .intValue();
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "maxLength is [" + maxLength + "]");
                        if (!GenericValidator.maxLength(value, maxLength)) {

                            params = new Vector();
                            params.add(fieldLabel);
                            params.add(String.valueOf(maxLength));

                            errorHandler.addError(
                                    new EMFUserError(EMFErrorSeverity.ERROR, ERROR_MAXLENGTH, params));

                        }
                    }
                } else if (validatorName.equalsIgnoreCase("MINLENGTH")) {
                    if (!GenericValidator.isBlankOrNull(value)) {
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Apply the MINLENGTH VALIDATOR to field [" + field + "] with value [" + value
                                        + "]");
                        int minLength = Integer.valueOf((String) currentValidator.getAttribute("arg0"))
                                .intValue();
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "minLength is [" + minLength + "]");
                        if (!GenericValidator.minLength(value, minLength)) {

                            // Generate Errors
                            params = new Vector();
                            params.add(fieldLabel);
                            params.add(String.valueOf(minLength));

                            errorHandler.addError(
                                    new EMFUserError(EMFErrorSeverity.ERROR, ERROR_MINLENGTH, params));

                        }
                    }
                } else if (validatorName.equalsIgnoreCase("REGEXP")) {
                    if (!GenericValidator.isBlankOrNull(value)) {
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Apply the REGEXP VALIDATOR to field [" + field + "] with value [" + value
                                        + "]");
                        String regexp = (String) currentValidator.getAttribute("arg0");
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "regexp is [" + regexp + "]");
                        if (!(GenericValidator.matchRegexp(value, regexp))) {

                            //                      Generate Errors
                            params = new Vector();
                            params.add(fieldLabel);
                            params.add(regexp);

                            errorHandler
                                    .addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_REGEXP, params));

                        }
                    }
                } else if (validatorName.equalsIgnoreCase("DATE")) {
                    if (!GenericValidator.isBlankOrNull(value)) {
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Apply the DATE VALIDATOR to field [" + field + "] with value [" + value + "]");
                        String dateFormat = (String) currentValidator.getAttribute("arg0");
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "dateFormat is [" + dateFormat + "]");
                        if (!GenericValidator.isDate(value, dateFormat, true)) {

                            //Generate Errors
                            params = new Vector();
                            params.add(fieldLabel);
                            params.add(dateFormat);

                            errorHandler.addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_DATE, params));
                        }
                    }

                }
            } //while (itValidators.hasNext())

        } catch (Exception ex) {
            TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.INFORMATION,
                    "ValidationModule::automaticValidation", ex);

        }

    }

}

From source file:jp.terasoluna.fw.validation.FieldChecks.java

/**
 * ???????/*from   w w w . j  a v  a  2s  .  c o  m*/
 *
 * <p>???10???????
 * true?????
 *
 * <h5>validation.xml?</h5>
 * <code><pre>
 * &lt;form name=&quot;sample&quot;&gt;
 *  
 *  &lt;field property=&quot;stringField&quot;
 *      depends=&quot;minLength&quot;&gt;
 *    &lt;arg key=&quot;sample.stringField&quot; position="0"/&gt;
 *    &lt;var&gt;
 *      &lt;var-name&gt;minlength&lt;/var-name&gt;
 *      &lt;var-value&gt;10&lt;/var-value&gt;
 *    &lt;/var&gt;
 *  &lt;/field&gt;
 *  
 * &lt;/form&gt;
 * </pre></code>
 *
 * <h5>validation.xml???&lt;var&gt;?</h5>
 * <table border="1">
 *  <tr>
 *   <td><center><b><code>var-name</code></b></center></td>
 *   <td><center><b><code>var-value</code></b></center></td>
 *   <td><center><b></b></center></td>
 *   <td><center><b>?</b></center></td>
 *  </tr>
 *  <tr>
 *   <td> minlength </td>
 *   <td>?</td>
 *   <td>true</td>
 *   <td>???
 *   ????????</td>
 *  </tr>
 * </table>
 *
 * @param bean ?JavaBean
 * @param va ?<code>ValidatorAction</code>
 * @param field ?<code>Field</code>
 * @param errors ?????
 * ??
 * @return ??????<code>true</code>?
 * ????<code>false</code>?
 * @throws ValidatorException validation??????
 * ?
 */
public boolean validateMinLength(Object bean, ValidatorAction va, Field field, ValidationErrors errors)
        throws ValidatorException {
    // 
    String value = extractValue(bean, field);
    if (StringUtils.isEmpty(value)) {
        return true;
    }

    // ??
    int min = 0;
    try {
        min = Integer.parseInt(field.getVarValue("minlength"));
    } catch (NumberFormatException e) {
        String message = "Mistake on validation definition file. " + "- minlength is not number. "
                + "You'll have to check it over. ";
        log.error(message, e);
        throw new ValidatorException(message);
    }

    // 
    if (!GenericValidator.minLength(value, min)) {
        rejectValue(errors, field, va, bean);
        return false;
    }
    return true;
}

From source file:org.apache.struts.validator.FieldChecks.java

/**
 * Checks if the field's length is greater than or equal to the minimum
 * value. A <code>Null</code> will be considered an error.
 *
 * @param bean      The bean validation is being performed on.
 * @param va        The <code>ValidatorAction</code> that is currently
 *                  being performed./*w w w  .  j  ava  2  s  .c o m*/
 * @param field     The <code>Field</code> object associated with the
 *                  current field being validated.
 * @param errors    The <code>ActionMessages</code> object to add errors
 *                  to if any validation errors occur.
 * @param validator The <code>Validator</code> instance, used to access
 *                  other field values.
 * @param request   Current request object.
 * @return True if stated conditions met.
 */
public static boolean validateMinLength(Object bean, ValidatorAction va, Field field, ActionMessages errors,
        Validator validator, HttpServletRequest request) {
    String value = null;

    value = evaluateBean(bean, field);

    if (!GenericValidator.isBlankOrNull(value)) {
        try {
            String minVar = Resources.getVarValue("minlength", field, validator, request, true);
            int min = Integer.parseInt(minVar);

            boolean isValid = false;
            String endLth = Resources.getVarValue("lineEndLength", field, validator, request, false);
            if (GenericValidator.isBlankOrNull(endLth)) {
                isValid = GenericValidator.minLength(value, min);
            } else {
                isValid = GenericValidator.minLength(value, min, Integer.parseInt(endLth));
            }

            if (!isValid) {
                errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));

                return false;
            }
        } catch (Exception e) {
            processFailure(errors, field, "minlength", e);

            return false;
        }
    }

    return true;
}

From source file:org.hyperic.util.validator.common.CommonValidatorUtil.java

/**
 * Validates a password field which restricts the length
 * between PASSWORD_MIN_LENGTH and PASSWORD_MAX_LENGTH
 *
 * @param bean containing the fields to validate.
 * @param Field object containing the property resource info.
 * //from   w w w  . j a  va2s.c om
 */
public static boolean validatePassword(Object bean, Field field) {
    boolean valid = false;
    // fetch the text to validate and enforce
    String pwd = ValidatorUtils.getValueAsString(bean, field.getProperty());
    if ((pwd != null) && (GenericValidator.minLength(pwd, PASSWORD_MIN_LENGTH))
            && (GenericValidator.maxLength(pwd, PASSWORD_MAX_LENGTH)))
        valid = true;
    return valid;
}