CodeValidator.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      https://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.validator.routines;

  18. import java.io.Serializable;

  19. import org.apache.commons.validator.GenericValidator;
  20. import org.apache.commons.validator.routines.checkdigit.CheckDigit;

  21. /**
  22.  * Generic <strong>Code Validation</strong> providing format, minimum/maximum
  23.  * length and {@link CheckDigit} validations.
  24.  * <p>
  25.  * Performs the following validations on a code:
  26.  * <ul>
  27.  *   <li>if the code is null, return null/false as appropriate</li>
  28.  *   <li>trim the input. If the resulting code is empty, return null/false as appropriate</li>
  29.  *   <li>Check the <em>format</em> of the code using a <em>regular expression.</em> (if specified)</li>
  30.  *   <li>Check the <em>minimum</em> and <em>maximum</em> length  (if specified) of the <em>parsed</em> code
  31.  *      (that is, parsed by the <em>regular expression</em>).</li>
  32.  *   <li>Performs {@link CheckDigit} validation on the parsed code (if specified).</li>
  33.  *   <li>The {@link #validate(String)} method returns the trimmed, parsed input (or null if validation failed)</li>
  34.  * </ul>
  35.  * <p>
  36.  * <strong>Note</strong>
  37.  * The {@link #isValid(String)} method will return true if the input passes validation.
  38.  * Since this includes trimming as well as potentially dropping parts of the input,
  39.  * it is possible for a String to pass validation
  40.  * but fail the checkdigit test if passed directly to it (the check digit routines generally don't trim input
  41.  * nor do they generally check the format/length).
  42.  * To be sure that you are passing valid input to a method use {@link #validate(String)} as follows:
  43.  * <pre>
  44.  * Object valid = validator.validate(input);
  45.  * if (valid != null) {
  46.  *    some_method(valid.toString());
  47.  * }
  48.  * </pre>
  49.  * <p>
  50.  * Configure the validator with the appropriate regular expression, minimum/maximum length
  51.  * and {@link CheckDigit} validator and then call one of the two validation
  52.  * methods provided:</p>
  53.  *    <ul>
  54.  *       <li>{@code boolean isValid(code)}</li>
  55.  *       <li>{@code String validate(code)}</li>
  56.  *    </ul>
  57.  * <p>
  58.  * Codes often include <em>format</em> characters - such as hyphens - to make them
  59.  * more easily human-readable. These can be removed prior to length and check digit
  60.  * validation by specifying them as a <em>non-capturing</em> group in the regular
  61.  * expression (that is, use the {@code (?:   )} notation).
  62.  * <br>
  63.  * Or just avoid using parentheses except for the parts you want to capture
  64.  *
  65.  * @since 1.4
  66.  */
  67. public final class CodeValidator implements Serializable {

  68.     private static final long serialVersionUID = 446960910870938233L;

  69.     /** The format regular expression validator. */
  70.     private final RegexValidator regexValidator;

  71.     /** The minimum length of the code. */
  72.     private final int minLength;

  73.     /** The maximum length of the code. */
  74.     private final int maxLength;

  75.     /** The check digit validation routine. */
  76.     private final CheckDigit checkdigit;

  77.     /**
  78.      * Constructs a code validator with a specified regular expression,
  79.      * validator and {@link CheckDigit} validation.
  80.      *
  81.      * @param regexValidator The format regular expression validator
  82.      * @param checkdigit The check digit validation routine.
  83.      */
  84.     public CodeValidator(final RegexValidator regexValidator, final CheckDigit checkdigit) {
  85.         this(regexValidator, -1, -1, checkdigit);
  86.     }

  87.     /**
  88.      * Constructs a code validator with a specified regular expression,
  89.      * validator, length and {@link CheckDigit} validation.
  90.      *
  91.      * @param regexValidator The format regular expression validator
  92.      * @param length The length of the code
  93.      *  (sets the minimum/maximum to the same value)
  94.      * @param checkdigit The check digit validation routine
  95.      */
  96.     public CodeValidator(final RegexValidator regexValidator, final int length, final CheckDigit checkdigit) {
  97.         this(regexValidator, length, length, checkdigit);
  98.     }

  99.     /**
  100.      * Constructs a code validator with a specified regular expression
  101.      * validator, minimum/maximum length and {@link CheckDigit} validation.
  102.      *
  103.      * @param regexValidator The format regular expression validator
  104.      * @param minLength The minimum length of the code
  105.      * @param maxLength The maximum length of the code
  106.      * @param checkdigit The check digit validation routine
  107.      */
  108.     public CodeValidator(final RegexValidator regexValidator, final int minLength, final int maxLength,
  109.             final CheckDigit checkdigit) {
  110.         this.regexValidator = regexValidator;
  111.         this.minLength = minLength;
  112.         this.maxLength = maxLength;
  113.         this.checkdigit = checkdigit;
  114.     }

  115.     /**
  116.      * Constructs a code validator with a specified regular
  117.      * expression and {@link CheckDigit}.
  118.      * The RegexValidator validator is created to be case-sensitive
  119.      *
  120.      * @param regex The format regular expression
  121.      * @param checkdigit The check digit validation routine
  122.      */
  123.     public CodeValidator(final String regex, final CheckDigit checkdigit) {
  124.         this(regex, -1, -1, checkdigit);
  125.     }

  126.     /**
  127.      * Constructs a code validator with a specified regular
  128.      * expression, length and {@link CheckDigit}.
  129.      * The RegexValidator validator is created to be case-sensitive
  130.      *
  131.      * @param regex The format regular expression.
  132.      * @param length The length of the code
  133.      *  (sets the minimum/maximum to the same)
  134.      * @param checkdigit The check digit validation routine
  135.      */
  136.     public CodeValidator(final String regex, final int length, final CheckDigit checkdigit) {
  137.         this(regex, length, length, checkdigit);
  138.     }

  139.     /**
  140.      * Constructs a code validator with a specified regular
  141.      * expression, minimum/maximum length and {@link CheckDigit} validation.
  142.      * The RegexValidator validator is created to be case-sensitive
  143.      *
  144.      * @param regex The regular expression
  145.      * @param minLength The minimum length of the code
  146.      * @param maxLength The maximum length of the code
  147.      * @param checkdigit The check digit validation routine
  148.      */
  149.     public CodeValidator(final String regex, final int minLength, final int maxLength,
  150.             final CheckDigit checkdigit) {
  151.         this.regexValidator = GenericValidator.isBlankOrNull(regex) ? null : new RegexValidator(regex);
  152.         this.minLength = minLength;
  153.         this.maxLength = maxLength;
  154.         this.checkdigit = checkdigit;
  155.     }

  156.     /**
  157.      * Gets the check digit validation routine.
  158.      * <p>
  159.      * <strong>N.B.</strong> Optional, if not set no Check Digit
  160.      * validation will be performed on the code.
  161.      *
  162.      * @return The check digit validation routine
  163.      */
  164.     public CheckDigit getCheckDigit() {
  165.         return checkdigit;
  166.     }

  167.     /**
  168.      * Gets the maximum length of the code.
  169.      * <p>
  170.      * <strong>N.B.</strong> Optional, if less than zero the
  171.      * maximum length will not be checked.
  172.      *
  173.      * @return The maximum length of the code or
  174.      * {@code -1} if the code has no maximum length
  175.      */
  176.     public int getMaxLength() {
  177.         return maxLength;
  178.     }

  179.     /**
  180.      * Gets the minimum length of the code.
  181.      * <p>
  182.      * <strong>N.B.</strong> Optional, if less than zero the
  183.      * minimum length will not be checked.
  184.      *
  185.      * @return The minimum length of the code or
  186.      * {@code -1} if the code has no minimum length
  187.      */
  188.     public int getMinLength() {
  189.         return minLength;
  190.     }

  191.     /**
  192.      * Gets the <em>regular expression</em> validator.
  193.      * <p>
  194.      * <strong>N.B.</strong> Optional, if not set no regular
  195.      * expression validation will be performed on the code.
  196.      *
  197.      * @return The regular expression validator
  198.      */
  199.     public RegexValidator getRegexValidator() {
  200.         return regexValidator;
  201.     }

  202.     /**
  203.      * Validate the code returning either {@code true}
  204.      * or {@code false}.
  205.      * <p>
  206.      * This calls {@link #validate(String)} and returns false
  207.      * if the return value is null, true otherwise.
  208.      * <p>
  209.      * Note that {@link #validate(String)} trims the input
  210.      * and if there is a {@link RegexValidator} it may also
  211.      * change the input as part of the validation.
  212.      *
  213.      * @param input The code to validate
  214.      * @return {@code true} if valid, otherwise
  215.      * {@code false}
  216.      */
  217.     public boolean isValid(final String input) {
  218.         return validate(input) != null;
  219.     }

  220.     /**
  221.      * Validate the code returning either the valid code or
  222.      * {@code null} if invalid.
  223.      * <p>
  224.      * Note that this method trims the input
  225.      * and if there is a {@link RegexValidator} it may also
  226.      * change the input as part of the validation.
  227.      *
  228.      * @param input The code to validate
  229.      * @return The code if valid, otherwise {@code null}
  230.      * if invalid
  231.      */
  232.     public Object validate(final String input) {
  233.         if (input == null) {
  234.             return null;
  235.         }
  236.         String code = input.trim();
  237.         if (code.isEmpty()) {
  238.             return null;
  239.         }
  240.         // validate/reformat using regular expression
  241.         if (regexValidator != null) {
  242.             code = regexValidator.validate(code);
  243.             if (code == null) {
  244.                 return null;
  245.             }
  246.         }
  247.         // check the length (must be done after validate as that can change the code)
  248.         if (minLength >= 0 && code.length() < minLength ||
  249.             maxLength >= 0 && code.length() > maxLength) {
  250.             return null;
  251.         }
  252.         // validate the check digit
  253.         if (checkdigit != null && !checkdigit.isValid(code)) {
  254.             return null;
  255.         }
  256.         return code;
  257.     }

  258. }