Skip to content

Validation

florin-botea edited this page Jan 21, 2022 · 3 revisions

Working with Validation.

use Aweb\Nexus\Validator;

You can make validations using Validator::make() method or Request::validate() (is calling Request::validate() and in case of error, redirects back with errors). Feel free to add your custom language files on nexus/lang folder and editing Aweb\Nexus\Validator to load them. English is default language for displayed errors.

Validator::make accepts as input validation data as first parameter, rules as second parameter, custom rule-messages as third and validated fields aliases as last parameter. See https://github.com/rakit/validation v1.0.0 for documentation about how it works.

Validation custom messages are templates of messages which will be populated with validated data. Fields are auto-aliased like this:

  • calling $this->language->all()
  • foreach validated key, check if there is an custom alias passed and use it
  • elseif entry_{validated_key} exists on loaded language, use it so, you have to load languages having named form-fields translated prefixed with entry_ in order to auto-alias them.
$validator->validate(Request::post(), [
    'name'                  => 'required',
];
// will search for an 'entry_name' on language keys and the message will be: 'The Name is required'

Validation errors are flashed on Session and available to display by calling Validator::error($key), or Validator::error() for accessing all errors as array. If you want to print a specific html string under each validated input, like <span class="text-danger">error here</span>, you can call echo Validator::errorDisplay($key)

<div class="form-group">
    <input type="text" name="name" class="form-control">
    <?php echo Validator::errorDisplay('name'); ?>
</div>

This will print the red text message only in case of error.

Clone this wiki locally