Posts Tagged ‘validation’

[ztemplates] Form validation with regular expressions

Sunday, November 16th, 2008

Today I tried form validation with ZTemplates. For validating something I had to use a regular expression. In my view I created a pattern matching property like this:

private final ZStringProperty name = new ZStringProperty() {
@Override
  public ZError validate() {
 
  try {
 
    ZError error = super.validate();
 
    if (error != null) {				
      return error;
    }
 
    final Matcher matcher = Pattern.compile("[A-Z]+").matcher(getValue());
 
    if (matcher.matches() == false) {
      return new ZError("You didn't supply a valid identifier");
    }
 
    return null;
 
    }
    catch (Exception e) {
      return new ZError(e.getMessage());
    }
  }
};

I then had to do 10 more, which annoyed me a bit. I decided to look at the in-built ZIntProperty type and then I built my own ‘ZPatternProperty’:

ZPatternProperty.java:

package org.ztemplates.property;
 
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
 
import org.ztemplates.property.ZProperty;
import org.ztemplates.web.ZTemplates;
 
public class ZPatternProperty extends ZProperty<String> {
 
  String pattern;
 
  public ZPatternProperty(String pattern, ZProperty<?>... dependsOn) {
 
    super(dependsOn);
    this.pattern = pattern;
  }
 
  public ZPatternProperty(String value, String pattern, ZProperty<?>... dependsOn) {
 
    super(dependsOn);
    this.pattern = pattern;
    setValue(value);
  }
 
  @Override
  public String parse(String formattedValue) throws Exception {
 
    if(formattedValue == null) {
      return null;
    }
 
    Pattern propertyPattern;
 
    try {
      propertyPattern = Pattern.compile(pattern);
    }
    catch(PatternSyntaxException e) {
 
    throw new Exception(ZTemplates.getMessageService().getMessage(ZPatternProperty.class.getName(), "PatternSyntaxException"));
    }
 
    // check if the value matches the pattern
    if(propertyPattern.matcher(formattedValue).matches() == false) {
      throw new Exception(ZTemplates.getMessageService().getMessage(ZPatternProperty.class.getName(), "NoMatchException"));
    }
 
    return formattedValue;
  }
 
  @Override
  public String format(String obj) {
    return obj;
  }
}

My first code example now becomes:

 
  private final ZPatternProperty name = new ZPatternProperty("[A-Z]+");

Isn’t that much more robust?!

I also had to supply a ZPatternProperties.properties file for getting the exception message:

ZPatternProperty.properties:

PatternSyntaxException=Invalid pattern
NoMatchException=Value does not match the pattern

It needs some better exception messages in the future, but for me it’s fine.

I’ve also sent an email to the creator of the ztemplates framework including the code. I hope that in a new version of ztemplates there will be support for pattern validation.