Validating user input
In the last example we have built a very simple login page. Of course in a real application we need to validate the data before we process it. This framework includes a simple to use validation part as well. Also the same convention over configuration applies as well. First we have to create a validator. All validators have to be in a "validator" subpackage and they have to extend the AbstractValidator
public class TestValidator extends AbstractValidator {
public void login() {
}
public String getName() {
return "test";
}
}
First of all you have to implement the getName method. The name must be the same as the controller. In our example the controller is called "test" and so the validator must be the same.
How does it work
During startup the framework will check all validators from the validator package and add them with the specific name to an internal map. Once there is a request for a specific controller the framework will check if there is an existing validator. In case it finds one this validator is executed before of course. The method names must simply match. So if you want to validate the input of your login page you need to create a method called "login". That is all. Later in your controller you can use the method "isValid()" to check if the input is correct.
Example
First we will write some logic to validate the input:
public void login() {
if ( isPostRequest() )
rejectEmpty("name","Please provide a username");
rejectEmpty("pwd","Please provide a password");
}
}
Of course we only validate the input if it is a POST reuqest. There are now many convenient methods available to check for example if a parameter is set at all.
The actual messages are added as error to Flash?.
Now you can simply change the logic of your controller like this:
public void login() {
if ( isPostRequest() && isValid() ) {
.....
}
}
Please note that any valid parameter is added to the view context automatically. Now we can change our view to this:
#if ( $flash.get("error") )
<h4>Errors occured</h4>
$flash.get("error")
#end
<form action='$vh.url("test","login")' method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="$!name"/>
<br/>
<label for="pwd">Password:</label>
<input type="password" id="pwd" name="pwd"/>
<br/>
<input type="submit" name="Login" value="Login"/>
</form>
The first block will use the flash to get the error messages from the validation method. In order to show the name in case it was valid just add the
value="$!name"