<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
	<channel>
		<title><![CDATA[Latest posts for the topic "Creating your own rules"]]></title>
		<link>http://book.mentaframework.org/posts/list/6.page</link>
		<description><![CDATA[Latest messages posted in the topic "Creating your own rules"]]></description>
		<generator>JForum - http://www.jforum.net</generator>
			<item>
				<title>Creating your own rules</title>
				<description><![CDATA[ A rule validates whether an action input value is valid or not to be passed along to the action. To learn about rules let's code a simple [i]NegativeRule [/i]class that validates only negative numbers.<br /> [code]<br /> import java.util.HashMap;<br /> import java.util.Map;<br /> <br /> <br /> public class NegativeRule extends BasicRule {<br /> 	<br /> 	public NegativeRule() { }<br /> 	<br /> 	public boolean check(String value) {<br /> 		<br /> 		try {<br /> 			<br /> 			int x = Integer.parseInt(value);<br />             <br />             return x &lt; 0;<br /> 			<br /> 		} catch(Exception e) {<br /> 			<br /> 			return false;<br /> 		}<br /> 	}<br />     <br /> 	public Map&lt;String, String&gt; getTokens() {<br /> 		return null; // no tokens...<br /> 	}<br />     <br /> }<br /> [/code]<br /> When you extend [i]BasicRule [/i]you should implement two methods: check() and getTokens().<br /> <br /> :arrow: check(String value): In this method you receive the value you are suppose to validate and just do it, however you want to, returning true or false.<br /> <br /> :arrow: getTokens(): In this method you return a map with tokens and their values to be used by error messages. The default implementation in BasicRule is to return null, so you should only implement this method if you have tokens to return.<br /> <br /> A token is used inside error messages so that it can be substituted for values associated with the rule. For example, in our simple rule above, the negative number has no minimum boundary. Let's change it to include a possible minimum:<br /> [code]<br /> import java.util.HashMap;<br /> import java.util.Map;<br /> <br /> <br /> public class NegativeRule extends BasicRule {<br />     <br />     private final int min;<br />     private final Map&lt;String, String&gt; tokens = new HashMap&lt;String, String&gt;();<br /> 	<br /> 	public NegativeRule() { <br />         this.min = Integer.MIN_VALUE;<br />         this.tokens.put("min", String.valueOf(min));<br />     }<br />     <br />     public NegativeRule(int min) {<br />         this.min = min;<br />         this.tokens.put("min", String.valueOf(min));<br />     }<br /> 	<br /> 	public boolean check(String value) {<br /> 		<br /> 		try {<br /> 			<br /> 			int x = Integer.parseInt(value);<br />             <br />             return x &lt; 0 && x &gt;= min;<br /> 			<br /> 		} catch(Exception e) {<br /> 			<br /> 			return false;<br /> 		}<br /> 	}<br />     <br /> 	public Map&lt;String, String&gt; getTokens() {<br /> 		return tokens;<br /> 	}<br /> }<br /> [/code]<br /> Note that now we have the possibility to validate the input value based on a minimum number and we are returning the token "min" with whatever value is given to that minimum number. Therefore you may have an error message like the one below:<br /> [code]<br /> invalid_number = Your negative number should be bigger than %min%.<br /> [/code]<br /> The %min% token is substituted with the value returned in the [i]getTokens() [/i]method. The [i]IntegerRule [/i]that comes with Mentawai also returns tokens for its min and max values. The tokens of a rule are nothing more than its properties that you may want to display along with the error messages.<br /> <br /> There are other types of validation that are not solely based in the value itself. For example you may want to perform validation based on the user locale and you may want to perform validation of one field based on another field.<br /> <br /> The most common example of a validation that depends on the locale is date validation. Depending on the user locale the date 12/30/2008 may be valid or not. Below is the source code of a simple rule to validate dates. Note that we are now extending [i]LocaleRule [/i]instead of [i]BasicRule[/i].<br /> [code]<br /> import java.util.*;<br /> import java.text.*;<br /> <br />  public class DateRule extends LocaleRule {<br /> 	 <br />      private static final int STYLE = DateFormat.SHORT;<br />      <br />      public DateRule() {<br />          <br />      }<br />      <br />      public boolean check(String value, Locale locale) {<br />     	 <br />          DateFormat df = DateFormat.getDateInstance(style, locale);<br />         	 <br />          df.setLenient(false);<br />          <br />          try {<br />              <br />              df.parse(value);<br />              <br />              return true;<br />              <br />          } catch(ParseException e) {<br />         	 <br />              return false;<br />              <br />          }<br />      }<br />      <br />      public Map&lt;String, String&gt; getTokens() {<br />     	 <br />     	 return null;<br />      }<br />      <br />  }<br /> [/code]<br /> Note that now the [i]check()[/i] method receives not just the value but also the locale of the user performing the request. You should use the locale in any way you want to perform the validation. Mentawai already comes with a complete [i]DateRule [/i]so you should not need to code a rule for dates. This was just an example for you to understand how the [i]LocaleRule [/i]works in case you want to write your own.<br /> <br /> The last form of common validation is when you need to compare two fields to determine whether one field is valid or not. If you thought about password and password confirmation you were right. For that we can extend the [i]CrossRule [/i]class. Check the source below for a simple [i]EqualRule [/i]that validates whether two fields have the same value:<br /> [code]<br /> import java.util.HashMap;<br /> import java.util.Map;<br /> <br /> public class EqualRule extends CrossRule {<br /> 	<br /> 	private final String[] fields;<br /> 	<br /> 	public EqualRule(String field1, String field2) {<br /> 		this.fields = new String[] { field1, field2 };<br /> 	}<br /> 	<br /> 	protected String[] getFieldsToValidate() {<br /> 		return fields;<br /> 	}<br /> 	<br /> 	public boolean check(String[] values) {<br /> 		<br /> 		return values[0].equals(values[1]);<br /> 	}<br /> 	<br /> 	public Map&lt;String, String&gt; getTokens() {<br /> 		return null;<br /> 	}<br /> }<br /> [/code]<br /> When inheriting from [i]CrossRule [/i]you should implement two abstract methods: <br /> <br /> :arrow: getFieldsToValidate() should return an array of the field names that will be compared.<br /> <br /> :arrow: check(String[] values) receives the values of the fields indicated by the[i] getFieldsToValidate()[/i] method, so that you can perform any comparison you want to validate them.<br /> <br /> Note that Mentawai gets the field values for you from the action input and pass them along with the check method so that you can compare them and return the validation result. Mentawai already comes with a complete [i]EqualRule [/i] in the [i]org.mentawai.rule[/i] package.<br /> <br /> Another very useful built-in rule that you can use for your advantage is the [i]RegexRule[/i]. Check below how a [i]SocialSecurityNumberRule [/i]could be implemented by inheriting from [i]RegexRule[/i]:<br /> [code]<br /> public class SSNRule extends RegexRule {<br /> 	<br />     /** The regex to use for SSN validation. */<br /> 	public static final String PATTERN = "^\\d\\d\\d\\-\\d\\d\\-\\d\\d\\d\\d$";<br /> 	<br /> 	public SSNRule() {<br /> 		super(PATTERN);<br /> 	}<br /> }<br /> [/code]<br /> You could have also used the [i]RegexRule [/i]with the Social Security Number pattern without the need to create a new rule for it. See below:<br /> [code]<br /> Rule rule = new RegexRule("^\\d\\d\\d\\-\\d\\d\\-\\d\\d\\d\\d$");<br /> [/code]<br /> As you can see, by inheriting from [i]BasicRule[/i], [i]LocaleRule[/i], [i]CrossRule [/i]and [i]RegexRule [/i]you can perform any kind of validation for your action input values.<br /> <br /> ]]></description>
				<guid isPermaLink="true">http://book.mentaframework.org/posts/preList/27/28.page</guid>
				<link>http://book.mentaframework.org/posts/preList/27/28.page</link>
				<pubDate><![CDATA[Mon, 11 Aug 2008 17:26:18]]> GMT</pubDate>
				<author><![CDATA[ saoj]]></author>
			</item>
	</channel>
</rss>