Validator Quickstart
To learn about validator features, let's look at a complete example of validating a form and displaying the error messages. I assume in this tutorial that your web framework is Spark but you can use what ever you want just read this page.
Defining context
Okay so we have a form to validate the inscription of an user. The fields are :
- Last ame
- First name
- Website (optional)
- Password
- Password confirmation
Let's code
First we need to defining the route :
post("/user/signin_validation", UserController::signup);
Next let's define UserController.signin()
:
public static Object signup(Request req, Response res) {
// Todo signup new user or throw error
}
Now need to instantiate a new Form
to handle inputs from user :
public static Object signup(Request req, Response res) {
SparkForm sp = new SparkForm(req);
}
For those who are wondering where the SparkForm
comes from, this is a proposal to implement the Form
class so that the Validator class can know where the information comes from or you need to create or find a class that implements Form
and implement the behaviors of the interface.
Now we need to instantiate the Validator
:
public static Object signup(Request req, Response res) {
SparkForm sp = new SparkForm(req);
Validator va = new Validator(sp);
}
By default language of error's message are in english. Consult this page page to know how to implement a language.
So now that we have our validator, we just need to add the rules that the user must follow. If one of the rules fails an error will return :
public static Object signup(Request req, Response res) {
SparkForm sp = new SparkForm(req);
Validator va = new Validator(sp);
try {
va
.addRule("lastname, firstname -> min_length: 3 | max_length: 25 | not_empty")
.addRule("website -> optional | url")
.addRule("email -> email | unique: users, email")
.addRule("password -> min_length: 5 | confirm");
} catch (RuleParseException ex) {
e.printStackTrace();
}
}
And finally we need to check if the new user can be added to the database or if we need to return an error message :
public static Object signup(Request req, Response res) {
SparkForm sp = new SparkForm(req);
Validator va = new Validator(sp);
try {
va
.addRule("lastname, firstname -> min_length: 3 | max_length: 25 | not_empty")
.addRule("email -> email | unique: users, email")
.addRule("password -> min_length: 5 | confirm");
} catch (RuleParseException ex) {
e.printStackTrace();
}
Map<String, String> check = va.check();
if (check.isEmpty()) {
// add user to the database
return new JSONObject().put("success", true).toString();
}
else
return new Gson().toJson(check);
}
And that's it ! Now you can focus on only what the website do and not how can i handle this fu**** form... :D