01: /*
02: * IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
03: *
04: * http://izpack.org/
05: * http://izpack.codehaus.org/
06: *
07: * Licensed under the Apache License, Version 2.0 (the "License");
08: * you may not use this file except in compliance with the License.
09: * You may obtain a copy of the License at
10: *
11: * http://www.apache.org/licenses/LICENSE-2.0
12: *
13: * Unless required by applicable law or agreed to in writing, software
14: * distributed under the License is distributed on an "AS IS" BASIS,
15: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16: * See the License for the specific language governing permissions and
17: * limitations under the License.
18: */
19:
20: package com.izforge.izpack.util;
21:
22: import com.izforge.izpack.panels.PasswordGroup;
23: import java.util.Map;
24: import java.util.regex.Pattern;
25:
26: import com.izforge.izpack.panels.ProcessingClient;
27: import com.izforge.izpack.panels.Validator;
28:
29: /**
30: * A validator to enforce non-empty fields.
31: *
32: * This validator can be used for rule input fields in the UserInputPanel to make sure that the
33: * user's entry matches a specified regular expression.
34: *
35: * @author Mike Cunneen <mike dot cunneen at screwfix dot com>
36: */
37: public class RegularExpressionValidator implements Validator {
38:
39: public static final String STR_PATTERN_DEFAULT = "[a-zA-Z0-9._-]{3,}@[a-zA-Z0-9._-]+([.][a-zA-Z0-9_-]+)*[.][a-zA-Z0-9._-]{2,4}";
40:
41: private static final String PATTERN_PARAM = "pattern";
42:
43: public boolean validate(ProcessingClient client) {
44:
45: String patternString;
46:
47: if (client.hasParams()) {
48: Map<String, String> paramMap = client.getValidatorParams();
49: patternString = paramMap.get(PATTERN_PARAM);
50: } else {
51: patternString = STR_PATTERN_DEFAULT;
52: }
53: Pattern pattern = Pattern.compile(patternString);
54: return pattern.matcher(getString(client)).matches();
55: }
56:
57: private String getString(ProcessingClient client) {
58: String returnValue = "";
59: if (client instanceof PasswordGroup) {
60: int numFields = client.getNumFields();
61: if (numFields > 0) {
62: returnValue = client.getFieldContents(0);
63: } else {
64: // Should never get here, but might as well try and grab some text
65: returnValue = client.getText();
66: }
67: } else {
68: // Original way to retrieve text for validation
69: returnValue = client.getText();
70: }
71: return returnValue;
72: }
73:
74: }
|