01: /*
02: * Copyright 2003 The Apache Software Foundation.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package velosurf.validation;
18:
19: import java.util.regex.Pattern;
20: import java.util.Locale;
21:
22: /**
23: * <p>A regular expression pattern constraint. Syntax is:</p>
24: * <pre>
25: * <<i>column</i> regex="<i>regex-pattern</i>"/>
26: * </pre>
27: *<p>Or:</p>
28: * <pre>
29: * <<i>column</i>>
30: * <regex pattern="<i>regex-pattern</i>" [message="<i>error-message</i>"] >
31: * </<i>column</i>>
32: * </pre>
33: * <p>Note: this constraint is not meant to replace an internal SQL constraint clause in the database,
34: * since it cannot be made sure that complex updates will respect this constraint.</p>
35: *
36: * @author <a href="mailto:claude.brisson@gmail.com">Claude Brisson</a>
37: */
38: public class Regex extends FieldConstraint {
39:
40: /** pattern. */
41: private Pattern pattern = null;
42:
43: /**
44: * Constructor.
45: * @param pattern the regex pattern to be matched
46: */
47: public Regex(Pattern pattern) {
48: this .pattern = pattern;
49: setMessage("field {0}: value '{1}' is not valid");
50: }
51:
52: /**
53: * Validate data against this constraint.
54: * @param data the data to be validated
55: * @return true if data matches the regex pattern
56: */
57: public boolean validate(Object data) {
58: return data == null || data.toString().length() == 0
59: || pattern.matcher(data.toString()).matches();
60: }
61:
62: /**
63: * return a string representation for this constraint.
64: * @return string
65: */
66: public String toString() {
67: return "regular expression " + pattern;
68: }
69: }
|