Want to create custom validation rules with parameter in Laravel - laravel

I want to add a custom validation rules with parameter and in the Laravel documentation https://laravel.com/docs/5.8/validation#custom-validation-rules there is no validation parameters option. I want a validation rule like required_if.

You can pass it in the constructor
new CustomRule($parameter);
class CustomRule implements Rule
{
public function __construct($parameter)
{
$this->parameter = $parameter;
}
...

You can use sometimes method on validator instance. Use a required rules and add your condition in the function as below:
$v->sometimes('reason', 'required|max:500', function ($input) {
return $input->games >= 100;
});
The example above will check if games are more than or equal to 100, then user will required to have a reason, otherwise it will trigger an error.
The example is from Laravel documentation that you can find here here

Related

Laravel route variables with multiple "-"

So I've got a category route in my laravel application looking like this:
Route::get('all-{category}-listings', 'CategoryController#index')->name('category');
When I go to the following URL localhost:8000/all-test-listings, it works fine,
but when a category also has a hyphen in it's name it gives me a 404, for example localhost:8000/all-test-test-listings
Does anyone know a way to solve this?
You can use "Regular Expression Constraints" on your route to enable categories with a dash:
Route::get('all-{category}-listings', 'CategoryController#index')
->where('category', '[A-Za-z0-9-]+')
->name('category');
https://laravel.com/docs/7.x/routing#parameters-regular-expression-constraints
If you would like a route parameter to always be constrained by a
given regular expression, you may use the pattern method. You should
define these patterns in the boot method of your
RouteServiceProvider:
/**
* Define your route model bindings, pattern filters, etc.
*
* #return void
*/
public function boot()
{
Route::pattern('category', '[a-z0-9-]+');
parent::boot();
}
Once the pattern has been defined, it is automatically applied to all
routes using that parameter name:
Route::get('all-{category}-listings', function ($category) {
// {category} has to be alpha numeric (lowercase), but can include a dash
});

CakePHP 3.x calling standard validation rules in own validation rules

How can I call the CakePHP 3.x built-in 'rule'=>'email' inside of my own validation rule? I would like to make this check among other customized checks not in e.g. validationDefault function.
public function myValidationRule($value,$context){
// HERE -- how can I call standard email rule
}
Except for requirePresence, allowEmpty and notEmpty, all built-in rules map to corresponding static methods on the \Cake\Validation\Validation class, which you can invoke manually yourself if necessary.
The email rule uses Validation::email(), so you can use it like
public function myValidationRule($value, $context) {
// ...
$isValid = \Cake\Validation\Validation::email($value);
// ...
}
See also
Cookbook > Validation > Core Validation Rules
API > \Cake\Validation\Validation::email()
public function myValidationRule($value,$context){
// HERE -- you can get your email in $value and other values in $context
// HERE you can add any of your custome validation rule
// for example
return $value==null;
// it will return true if your email is null.
}

custom Laravel Validation Rule example

I'm having difficulty figuring out how to write a custom validation rule in Laravel 5.1. I've read the documentation, but it seems incomplete. Looking it over, I just don't see where I'm supposed to put my actual validation logic, such as if (stristr($string, 'test')) { ... and so on.
For another thing, it doesn't show in what method/array the error message defintions should go:
"foo" => "Your input was invalid!",
"accepted" => "The :attribute must be accepted.",
// The rest of the validation error messages...
My actual use case is somewhat strange, so for this question, let's use the example of validating a secure password. A secure password must be at least 8 characters long, containing a lowercase and uppercase letter, a number and a special character.
Actually, that's a pretty tall order for an example, so how about just checking for a number? Or running any string function on the value?
How would one create such a validation rule?
As described in the document you've linked, you need to put your validation logic inside the boot function of a ServiceProvider, (e.g. AppServiceProvider) by using the static extend method.
Here is a short example (associated with the example in the docs).
<?php
namespace App\Providers;
use Validator;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Validator::extend('yourFunctionNameHere', function($attribute, $value, $parameters, $validator) {
return $value == 'yourTestValueHere'; //change the body as you need it
});
}
}
The input of the user is assigned to $value

Yii2 : How to validate XSS (Cross Site Scripting) in form / model input?

Yii2 has support for XSS(cross-site-scripting ) validation of displayed data using the helper class\yii\helpers\HtmlPurifier, however this only validates and cleans up output code like this
echo HtmlPurifier::process($html);
How to validate input for XSS of input such that this data is not stored in the database itself ?
This can be done using a filterValidator by calling the process as named callable function of validation like this
class MytableModel extends ActiveRecord {
....
public function rules(){
$rules = [
[['field1','field2'],'filter','filter'=>'\yii\helpers\HtmlPurifier::process']
];
return array_merge(parent::rules(),$rules);
}
....
}
Where field1, field2 etc are the inputs fields to be validated, the same applies for Form Model validations as well
in the before validate method add the following:
public function beforeValidate()
{
foreach (array_keys($this->getAttributes()) as $attr){
if(!empty($this->$attr)){
$this->$attr = \yii\helpers\HtmlPurifier::process($this->$attr);
}
}
return parent::beforeValidate();// to keep parent validator available
}
it will help you if you want to run Xss Validator before validate/save all attributes nested of adding the following line
return array_merge(parent::rules(),$rules);
to every class extends the new active record

Override URL validation rule to tolerate whitespaces at ends of URL

I would like to override the standard URL validation rule to make it more tolerant of a whitespace character before or after the URL. Basically use the trim() function on the url before passing it to the standard URL validation handler.
I know I need to override that rule but I'm not exactly where and how I need to do it.
(Plus, the CakePHP API and book documentation are currently offline. Upgrades, I know...)
You can add custom validation rules in your Model classes, your Behavior classes, or in the AppModel class:
http://book.cakephp.org/view/150/Custom-Validation-Rules#Adding-your-own-Validation-Methods-152
Since you want to override an existing method, just give it the same name and signature as the original. Something like this might do the trick:
function url($check, $strict = false) {
return Validation::url(trim($check), $strict);
}
Why would you wanna do that?
Simply make sure all posted data is always trimmed.
Thats cleaner and more secure, anyway.
I have a component doing that in beforeFilter:
/** DATA PREPARATION **/
if (!empty($controller->data) && !Configure::read('DataPreparation.notrim')) {
$controller->data = $this->trimDeep($controller->data);
}
The trimDeep method:
/**
* #static
*/
function trimDeep($value) {
$value = is_array($value) ? array_map(array(&$this, 'trimDeep'), $value) : trim($value);
return $value;
}

Resources