View Javadoc
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  
19  import java.text.DecimalFormat;
20  import java.text.Format;
21  
22  /**
23   * <p><strong>Currency Validation</strong> and Conversion routines ({@code java.math.BigDecimal}).</p>
24   *
25   * <p>This is one implementation of a currency validator that has the following features:</p>
26   *    <ul>
27   *       <li>It is <em>lenient</em> about the presence of the <em>currency symbol</em></li>
28   *       <li>It converts the currency to a {@code java.math.BigDecimal}</li>
29   *    </ul>
30   *
31   * <p>However any of the <em>number</em> validators can be used for <em>currency</em> validation.
32   *    For example, if you wanted a <em>currency</em> validator that converts to a
33   *    {@code java.lang.Integer} then you can simply instantiate an
34   *    {@code IntegerValidator} with the appropriate <em>format type</em>:</p>
35   *
36   *    <p>{@code ... = new IntegerValidator(false, IntegerValidator.CURRENCY_FORMAT);}</p>
37   *
38   * <p>Pick the appropriate validator, depending on the type (for example, Float, Double, Integer, Long and so on)
39   *    you want the currency converted to. One thing to note - only the CurrencyValidator
40   *    implements <em>lenient</em> behavior regarding the currency symbol.</p>
41   *
42   * @since 1.3.0
43   */
44  public class CurrencyValidator extends BigDecimalValidator {
45  
46      private static final long serialVersionUID = -4201640771171486514L;
47  
48      private static final CurrencyValidator VALIDATOR = new CurrencyValidator();
49  
50      /** DecimalFormat's currency symbol */
51      private static final char CURRENCY_SYMBOL = '\u00A4';
52  
53      /**
54       * Gets the singleton instance of this validator.
55       * @return A singleton instance of the CurrencyValidator.
56       */
57      public static BigDecimalValidator getInstance() {
58          return VALIDATOR;
59      }
60  
61      /**
62       * Constructs a <em>strict</em> instance.
63       */
64      public CurrencyValidator() {
65          this(true, true);
66      }
67  
68      /**
69       * Constructs an instance with the specified strict setting.
70       *
71       * @param strict {@code true} if strict
72       *        {@code Format} parsing should be used.
73       * @param allowFractions {@code true} if fractions are
74       *        allowed or {@code false} if integers only.
75       */
76      public CurrencyValidator(final boolean strict, final boolean allowFractions) {
77          super(strict, CURRENCY_FORMAT, allowFractions);
78      }
79  
80      /**
81       * <p>Parse the value with the specified {@code Format}.</p>
82       *
83       * <p>This implementation is lenient whether the currency symbol
84       *    is present or not. The default {@code NumberFormat}
85       *    behavior is for the parsing to "fail" if the currency
86       *    symbol is missing. This method re-parses with a format
87       *    without the currency symbol if it fails initially.</p>
88       *
89       * @param value The value to be parsed.
90       * @param formatter The Format to parse the value with.
91       * @return The parsed value if valid or {@code null} if invalid.
92       */
93      @Override
94      protected Object parse(final String value, final Format formatter) {
95  
96          // Initial parse of the value
97          Object parsedValue = super.parse(value, formatter);
98          if (parsedValue != null || !(formatter instanceof DecimalFormat)) {
99              return parsedValue;
100         }
101 
102         // Re-parse using a pattern without the currency symbol
103         final DecimalFormat decimalFormat = (DecimalFormat) formatter;
104         final String pattern = decimalFormat.toPattern();
105         if (pattern.indexOf(CURRENCY_SYMBOL) >= 0) {
106             final StringBuilder buffer = new StringBuilder(pattern.length());
107             for (int i = 0; i < pattern.length(); i++) {
108                 if (pattern.charAt(i) != CURRENCY_SYMBOL) {
109                     buffer.append(pattern.charAt(i));
110                 }
111             }
112             decimalFormat.applyPattern(buffer.toString());
113             parsedValue = super.parse(value, decimalFormat);
114         }
115         return parsedValue;
116     }
117 }