Ticket #680 (new enhancement)
Validator: Regular expression functionality
| Reported by: | Jani Laakso | Owned by: | Jani Laakso |
|---|---|---|---|
| Priority: | major | Milestone: | IT Mill Sponsored Backlog |
| Component: | Server-side framework | Version: | 5.2.0-rc |
| Keywords: | Cc: | jukka.viitala@… | |
| Known Issue description: | |||
| Hours estimate: | 2 | Deadline (dd.mm.yyyy): | |
| Known Issue version (since): | Known Issue title: | ||
| Hours done: | Depends to: | ||
| Affects documentation: | no | ||
| Known Issue workaround: | |||
| Affects release notes: | yes | Contract: | |
Description
Jukka has created following validator with his customer project
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.millstone.base.data.Validator;
/**
* Validates a string against a given regular expression.
*
* @author Oy IT Mill Ltd
*
*/
public class RegularExpressionValidator implements Validator {
private boolean allowNull;
private String message;
private String reqularExpression;
private Pattern pattern;
/**
*
* @param message
* to put on exception if value is not valid.
* @param regularExpression
* that is compiled to Pattern just before validation.
* @param allowNull,
* if <code>true</code> the null or empty value is valid.
*/
public RegularExpressionValidator(String message, String regularExpression, boolean allowNull) {
this.allowNull = allowNull;
this.message = message;
if (regularExpression == null)
throw new IllegalArgumentException("Regular expression must not be null.");
this.reqularExpression = regularExpression;
}
/**
*
* @param message
* to put on exception if value is not valid.
* @param pattern
* @param allowNull,
* if <code>true</code> the null or empty value is valid.
*/
public RegularExpressionValidator(String message, Pattern pattern, boolean allowNull) {
this.allowNull = allowNull;
if (pattern == null)
throw new IllegalArgumentException("Pattern must not be null.");
this.pattern = pattern;
this.message = message;
}
public boolean isValid(Object value) {
String str = value.toString();
if (allowNull && (str == null || "".equals(str.toString())))
return true;
// Pattern compilation is postponed to here
if (this.pattern == null)
pattern = Pattern.compile(this.reqularExpression);
Matcher matcher = pattern.matcher((CharSequence) str);
return matcher.matches();
}
public void validate(Object value) throws InvalidValueException {
if (!isValid(value))
throw new InvalidValueException(message);
}
}
Change History
Note: See
TracTickets for help on using
tickets.
