001    package hirondelle.web4jtools.util;
002    
003    import hirondelle.web4j.model.Validator;
004    import hirondelle.web4j.security.SafeText;
005    import java.util.regex.*;
006    
007    /**
008    * Custom validations. 
009    * 
010    * <P>This is an example of extending the framework's <tt>Check</tt> class with 
011    * custom validations. Note that the name of this class is the same as the name of 
012    * the framework class. This is unusual. It allows the calling code to retain the same 
013    * look when using custom validations.
014    */
015    public final class Check extends hirondelle.web4j.model.Check {
016    
017      /**
018      * Return <tt>true</tt> only if <tt>Object.toString()</tt> forms a valid regular expression. 
019      * <P>If the <tt>Object</tt> is an instance of <tt>SafeText</tt>, then perform the test on 
020      * <tt>SafeText.getRawString()</tt> instead. 
021      */
022      public static Validator isRegex(){
023        class CheckRegex implements Validator {
024          public boolean isValid(Object aObject) {
025            boolean result = true;
026            String pattern = null;
027            
028            if ( aObject instanceof SafeText ) {
029              SafeText safeText = (SafeText)aObject;
030              pattern = safeText.getRawString();
031            }
032            else {
033              pattern = aObject.toString();
034            }
035            
036            try {
037              Pattern regex = Pattern.compile(pattern);
038            }
039            catch (PatternSyntaxException ex){
040              result = false;
041            }
042            return result;
043          }
044        }
045         return new CheckRegex();
046      }
047    }