com.bagdemir.eboda.validator.PageNumberValidator.java Source code

Java tutorial

Introduction

Here is the source code for com.bagdemir.eboda.validator.PageNumberValidator.java

Source

/*
 *   Copyright (C) 2013 "Erhan Bagdemir"
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.bagdemir.eboda.validator;

import org.apache.commons.lang.StringUtils;

public class PageNumberValidator implements Validator<String, Integer> {

    @Override
    public ValidationResult<Integer> validate(final String input) {

        final ValidationResult<Integer> validationResult = new ValidationResult<>();

        if (StringUtils.isBlank(input)) {
            registerError(validationResult, "Page number shouldn't be an integer value: null");
        } else {
            validatePageNumber(input, validationResult);
        }
        return validationResult;
    }

    private void validatePageNumber(final String input, final ValidationResult<Integer> validationResult) {
        try {
            int pageNumber = Integer.parseInt(input);
            if (pageNumber > 0) {
                validationResult.setInput(pageNumber);
                validationResult.setValid(true);
            } else {
                registerError(validationResult, "Page number shouldn't be a negativ number.");
            }
        } catch (NumberFormatException exception) {
            registerError(validationResult, String.format("Page number shouldn't be an integer value: %s", input));
        }
    }

    private void registerError(final ValidationResult<Integer> validationResult, final String message) {
        validationResult.setValid(false);
        validationResult.setError(message);
    }
}