Leaf Forms
Leaf Form contains methods to simply and quickly handle input from the user.
Installation
You can quickly install leaf forms using the following composer or the leaf cli.
leaf install form
or with composer
composer require leafs/form
Functional Mode
Leaf form now supports leaf 3's functional mode which allows you to simply call the form
method from anywhere in your code. This returns an instance of the Leaf\Form
class, so in case you can't use functional mode, simply call your method on Leaf\Form
.
form()->sanitizeInput(...);
Form class
Leaf form can be used by initializing the leaf form class.
$form = new Leaf\Form;
$form->sanitizeInput(...);
sanitizeInput
sanitizeInput offers basic security for input data, i.e. sanitizing input against SQL injection.
$username = form()->sanitizeInput($username);
$username = $form->sanitizeInput($username);
If you however need better sanitizing, you can check out the anchor module
Form Submit
This creates a form and submits it. You can call it a virtual form. It takes in 3 parameters, the request type, the form action and the form data. Currently, it only supports GET and POST requests.
form()->submit("POST", "/book/create", [
"title" => "Book One",
"author" => "Mychi"
]);
$form->submit("POST", "/book/create", [
"title" => "Book One",
"author" => "Mychi"
]);
isEmail
This checks if a field contains an email or not.
if (form()->isEmail($field)) {
echo "This is an email";
}
if ($form->isEmail($field)) {
echo "This is an email";
}
body
This returns all fields passed into a request as an array.
$data = form()->body();
$data = $form->body();
Validation
Validation is one of the most important features used in many different types of projects. Leaf Forms provides a very simple way to validate fields returned from forms, json data and even urls and files.
Validate
Validate simply makes sure that the selected parameters pass these validation tests.
Parameters which fail the form validation are saved in the form's errors which can be accessed with errors()
. So In case the validation fails, validate
returns false, else true.
$validatorSuccess = form()->validate([
"username" => "username",
"email" => "email",
"password" => "required"
]);
if (!$validatorSuccess) {
response()->exit(form()->errors());
}
$validatorSuccess = $form->validate([
"username" => "username",
"email" => "email",
"password" => "required"
]);
if (!$validatorSuccess) {
response()->exit($form->errors());
}
Inline validate
For single rules, using an array takes up a few more lines and looks a bit clustered. For those cases, you can run your validation rules inline:
$validation = form()->validate('firstname', 'nospaces');
if (!$validation) {
response()->exit(form()->errors());
}
$validation = $form->validate('firstname', 'nospaces');
if (!$validation) {
response()->exit($form->errors());
}
validateData
validateData works pretty much the same way as validate
except that instead of passing the name of the field you want to validate, you validate the data itself.
form()->validateData([
"mychi.darko" => "validUsername",
"mychi@leafphp.dev" => "email"
]);
$form->validateData([
"mychi.darko" => "validUsername",
"mychi@leafphp.dev" => "email"
]);
validateField
This method also allows you validate data, but compared, to the method above, this is much faster.
form()->validateField("username", "michael", "validUsername");
$form->validateField("username", "michael", "validUsername");
Multiple Rule Validation
You can also pass an array as the rule parameter. If there's more than one rule, both of them will apply. Also, be sure not to use contradictory rules like number
and textOnly
or username
and email
.
form()->validate([
"username" => "validUsername",
"email" => "email",
"password" => ["required", "noSpaces"]
]);
form()->validate('username', 'validUsername');
$form->validate([
"username" => "validUsername",
"email" => "email",
"password" => ["required", "noSpaces"]
]);
$form->validate('username', 'validUsername');
Supported rules
This is a list of all supported validate rules
required
: field is requirednumber
: must only contain numberstext
: must only contain text and spacestextOnly
: should be text only, no spaces allowedvalidUsername
: must only contain characters 0-9, A-Z and _username
: alias for validUsernameemail
: must be a valid emailnoSpaces
: can't contain any spacesmax
: max length of a string (requires arguments)min
: min length of a string (requires arguments)date
: string should be a valid date
Note that these rules aren't case-sensitive, so you can type them anyway you prefer, as long as the spelling is the same.
Custom Error Messages
This has been one of the most sought after features in leaf form, and now it comes pre-packaged in this version. Using custom error messages, you can take your app a step further and define custom error messages in your language of choice. You can do this using the messages
method.
form()->messages('nospaces', '{field} no puede contener espacios');
$form->messages('nospaces', '{field} no puede contener espacios');
or
form()->messages('min', '{field} doit comporter au moins 8 caractères');
$form->messages('min', '{field} doit comporter au moins 8 caractères');
Note the use of {field}
. This is a mini template that tells leaf to replace {field} with the current field. So in this case:
$validation = form()->validate('password', 'min:8');
$validation = $form->validate('password', 'min:8');
{field}
will be replaced with password
. Leaf form also supports {value}
and {params}
which are basically the value of the field being checked and parameters passed into the current rule if any.
In the example above, {value}
will be the value of password
which the user passes into request, and {params}
will be 8
: that's the parameter passed to the min
rule.
Note
This only works for in-built rules, for custom rules, you can set your own error message using the addError
method as done below.
Create your own rules
Not every project is the same, as such, you might need validation rules which are not available by default in leaf. As such, the rule
method has been created to give you leeway to write your own validation rules.
You will need to use addError
to save error messages when the validation fails.
form()->rule("max", function ($field, $value, $params) {
if (strlen($value) > $params) {
form()->addError($field, "$field can't be more than $params characters");
return false;
}
});
$form->rule("max", function ($field, $value, $params) use($form) {
if (strlen($value) > $params) {
$form->addError($field, "$field can't be more than $params characters");
return false;
}
});
This is an example rule that makes sure that a string isn't longer than it should be. It takes in a $params
value which is the max length of the string.
To use this rule, you can simply call max and pass a value into the $params
field using :
.
form()->validate([
"username" => "max:10",
...
$form->validate([
"username" => "max:10",
...
Adding the params field is not compulsory, you can create a rule that doesn't take a params field like this:
form()->rule("required", function ($field, $value) {
if (($value == "" || $value == null)) {
form()->addError($field, "$field is required");
return false;
}
});
$form->rule("required", function ($field, $value) use($form) {
if (($value == "" || $value == null)) {
$form->addError($field, "$field is required");
return false;
}
});
This example doesn't take in any parameters.
supportedRules
You can also get all the supported rules. This includes custom rules you've created.
$formRules = form()->supportedRules();
$formRules = $form->supportedRules();
errors
Remember we talked about Leaf Form errors? Leaf Form holds errors for all failed tests, you get all these errors back with errors()
$validation = form()->validate([
"username" => "validUsername",
"email" => "email",
"password" => ["required", "noSpaces"]
]);
if (!$validation) {
return form()->errors();
}
$validation = $form->validate([
"username" => "validUsername",
"email" => "email",
"password" => ["required", "noSpaces"]
]);
if (!$validation) {
return $form->errors();
}