1 package com.opencsv.bean.validators;
2
3 import com.opencsv.bean.BeanField;
4 import com.opencsv.exceptions.CsvValidationException;
5
6 import java.util.ResourceBundle;
7
8 /**
9 * <p>This is a validator that, due to the addition of the parameter, allows the validation of multiple different types
10 * of input. The paramString must be a valid regular expression. The MustMatchRegularExpression validator will
11 * the {@link String#matches(String)} method on the string to be converted and the regular expression string and if
12 * the two do not match then a {@link CsvValidationException} will be thrown.</p>
13 * <p>Because this is validating the string <em>before</em> it is parsed/converted, the capture settings
14 * of the string must be taken into account.</p>
15 * <p>Examples:</p>
16 * <pre>
17 * // The String that becomes id must be a number with three to six digits.
18 * @PreAssignmentValidator(validator = MustMatchRegexExpression.class, paramString = "^[0-9]{3,6}$")
19 * @CsvBindByName(column = "id")
20 * private int beanId;
21 *
22 * // The String that becomes bigNumber must be a number with seven to ten digits.
23 * // The String for this field is after the word "value: " in the field.
24 * @PreAssignmentValidator(validator = MustMatchRegexExpression.class, paramString = "^[A-Za-z ]*value: [0-9]{7,10}$")
25 * @CsvBindByName(column = "big number", capture = "^[A-Za-z ]*value: (.*)$", format = "value: %s")
26 * private long bigNumber;
27 * </pre>
28 */
29 public class MustMatchRegexExpression implements StringValidator {
30 private String regex = "";
31
32 /**
33 * Default constructor.
34 */
35 public MustMatchRegexExpression() {
36 this.regex = "";
37 }
38
39 @Override
40 public boolean isValid(String value) {
41 if (regex.isEmpty()) {
42 return true;
43 }
44 return value.matches(regex);
45 }
46
47 @Override
48 public void validate(String value, BeanField field) throws CsvValidationException {
49 if (!isValid(value)) {
50 throw new CsvValidationException(String.format(ResourceBundle.getBundle("mustMatchRegex", field.getErrorLocale())
51 .getString("validator.regex.mismatch"), field.getField().getName(), value, regex));
52 }
53 }
54
55 @Override
56 public void setParameterString(String value) {
57 if (value != null && !value.isEmpty()) {
58 regex = value;
59 }
60 }
61 }