The simpliest way to add Respect/Validation into FluxCP
- Create new direcotry in
FLUX_ROOT/lib/
with namerespectvalidation
- Followed its installation guide by using command line in
respectvalidation
directory
composer require respect/validation
- In any module file you want to add the input validation (example: modules/character/view.php) add the respect/validation autoload
require 'respectvalidation/vendor/autoload.php';
use Respect\Validation\Validator;
use Respect\Validation\Exceptions\NestedValidationException;
- As example in this char view module, before
$charID = $params->get('id');
add the validation check (wrap it withtry { }
try {
$charID = $params->get('id');
Validator::numeric()->length(6,7)->setName('Char ID')->assert($charID);
/**
* Put original view.php after $charID = $params->get('id'); line into this 'try' bracket
**/
$col = "ch.char_id, ch.account_id, ch.char_num, ch.name AS char_name, ch.class AS char_class, ch.base_level AS char_base_level, ";
// ...
// ...
$itemAttributes = Flux::config('Attributes')->toArray();
}
} catch (NestedValidationException $exception) {
$errorMessage = $exception->getFullMessage();
$char = null;
}
- Then edit the theme file for char view themes/default/character/view.php. Edit to
<?php if (!defined('FLUX_ROOT')) exit; ?>
<h2>Viewing Character</h2>
<?php if (isset($errorMessage)): ?>
<p class="red"><?php echo htmlspecialchars($errorMessage) ?></p>
<?php endif ?>
This screenshot below when I set the validation rule as Validator::numeric()->length->(8,10)->setName('Char ID');
As the exception message from NestedValidationException
class may throws multiple lines for a single validation while getFullMessage()
returns the multiple line in markdown style and getMessages()
is in array!
Here's a quick styling guide.
- In module file, in catch block, change
$errorMessage = $exception->getFullMessage();
to
$errorMessage = "<ul class='red validation-error'>";
foreach ($exception->getMessages() as $i => $msg) {
$errorMessage .= "<li>- ".$msg."</li>";
}
$errorMessage .= "</ul>";
- Then because
<p>
never be friendly with<ul>
or<ol>
andhtmlspecialchars()
will remove the HTML chars also you can restyle it later instead recreate the error message as plain text with newline tag such<br />
, edit on view file
<p class="red"><?php echo htmlspecialchars($errorMessage) ?></p>
to
<?php if (isset($errorMessage)): ?>
<?php echo $errorMessage ?>
<?php endif ?>