Form validation in yii - validation

I trying to post form in yii but don't have any idea regarding validation, i go through some yii documentation but not getting it. can't we do validation without form object of yii? means in view i am using normal HTML for form of yii.

Validation is built into Yii in Models, whether it is Form models or CActiveRecord models.
In order to implement validation, place the validation rules in your model. In the example below, I am using an activerecord model.
class Customer extends CActiveRecord {
// :
public function rules(){
return array(
array('name, surname, email', 'required'),
array('age, email', 'length','min'=>18)
);
}
You can now validate ANY form, whether you are using Yii forms or plain HTML forms.
To enforce validation, your controller must populate the model values, then call upon the model to check the data against the rules you defined earlier.
class CustomerController extends CController {
// :
$customerModel = new Customer;
// Set fields using this format ...
$customerModel->attributes['name'] = $_FORM['user'];
// ...or this ...
$customerModel->age = $_FORM['age'];
// ...of this
$customerModel->setEmail($_FORM['email'];
// Now validate the model
if ($customerModel->validate) {
return true;
}
else {
return false;
}
// :
}
}

In action, you need to add
$this->performAjaxValidation($model);
in _form, add
'enableAjaxValidation'=>true,
and in model, you need to set rules,
public function rules(){
return array(
// array('username, email', 'required'), // Remove these fields from required!!
array('email', 'email'),
array('username, email', 'my_equired'), // do it below any validation of username and email field
);
}
I think, this will be helpful for you.

Related

Yii2 - Attributes in DynamicModel

I created a yii\base\DynamicModel in controller and I have one form with attributes from this model. I need access these attributes after submitting form in controller.
controller.php
public function actionCreate()
{
$model = new DynamicModel([
'name', 'age', 'city'
]);
if($model->load(Yii::$app->request->post())){
$model->age = $model->age + 5;
/*
* code....
* */
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
But $model->age, $model->name etc. returns nothing.
I could only access the attribute this way: Yii::$app->request->get('DynamicModel')['age']
What is the correct way to access these attributes?
You need to configure validation rules in order to automatically load attributes by load():
$model = new DynamicModel(['name', 'age', 'city']);
$model->addRule(['name', 'age', 'city'], 'safe');
if ($model->load(Yii::$app->request->post())) {
// ...
Using safe will accept values as is without actual validation, but you may consider adding real validation rules to ensure correct state of your model.

On the fly / dynamic CakePhp 3 Validation and FormHelper

I am creating a 'form editor' in CakePHP.
The interface allows the user to choose validations to apply to the fields, e.g. Numeric, Email etc.
As such I need to dynamically create validation for the model based on the user input. For this I can use the Validation object: https://book.cakephp.org/3.0/en/core-libraries/validation.html
I want to take advantage of the features of FormHelper, for example, automatically outputting error messages for fields.
I can see how to use a hard-coded validator from the model to do this by setting the validator in the context option for Form->create() - but how do I use a customer $Validator object which has been dynamically created?
Clarification:
I have some code in my controller:
//get the form configuration
$form = $this->Forms->get($id, ['contain'=>['FormFields'=>['Validations']]]);
//set up validation based on the configuration
$validator = new Validator();
foreach($form->form_fields as $field){
...
if($field->required) $validator->notBlank($field->field_name);
}
$table = TableRegistry::get($form->type);
$table->setValidator($validator);
Unfortunately setValidator() is not a method of TableRegistry.
If I set the validation up in the model, I would need the $id parameter to look up the correct form configuration.
I added the following code to my model:
protected $validator = null;
public function validationDefault(Validator $validator){
if($this->validator != null) return $this->validator;
return $validator;
}
public function setValidator(Validator $validator){
$this->validator = $validator;
}
So the default validator can effectively be set via the setValidator method.
Then in my controller:
//get the form configuration
$form = $this->Forms->get($id, ['contain'=>['FormFields'=>['Validations']]]);
//set up validation based on the configuration
$validator = new Validator();
foreach($form->form_fields as $field){
...
if($field->required) $validator->notBlank($field->field_name);
}
$table = TableRegistry::get($form->type);
$table->setValidator($validator);
I hope this is useful for others.

YII2 validation check unique between two fields without using active record

I am using two fields "old_password" and "new_password". I want the error message if value in both fields are same.
I am not using Activerecords.
I tried in model :
['a1', 'unique', 'targetAttribute' => 'a2']
but above code will work only for active record.
How can i get error message without using active record ?
You need to use compare validator instead of unique.
['new_password', 'compare', 'compareAttribute' => 'old_password', 'operator' => '!='],
Because unique validator validates that the attribute value is unique across the table
If your model extend yii\base\Model, activeRecerd are not necessary and you can use the rules function
public function rules()
{
return [
['a1', 'unique', 'targetAttribute' => 'a2'],
];
}
for assign your validation rules
and in your controller you can perform validation invoking $model->validation
$model = new \app\models\YourForm();
like suggested in Yii2 guide for validating input
// populate model attributes with user inputs
$model->load(\Yii::$app->request->post());
// which is equivalent to the following:
// $model->attributes = \Yii::$app->request->post('ContactForm');
if ($model->validate()) {
// all inputs are valid
} else {
// validation failed: $errors is an array containing error messages
$errors = $model->errors;
}

laravel 5 double validation and request

I did this validation and works:
public function salvar(CreateEquipamento $Vequip, CreateLocalizacao $VLocal)
{
$this->equipamento->create($Vequip->all());
$equipamento = $this->equipamento->create($input);
return redirect()->route('equipamento.index');
}
what I want is to also do something like get the last created equipment ID and include in the array to validate and create for Local validation (CreateLocalizacao $VLocal) because i've two tables, one for the equipment and another one who stores all the places where my equipment was in.
$input['equipamento_id'] = $equipamento->id;
$this->localizacao->create($VLocal->all());
How could I do something like this?? thx in advance !
I do a "workarround" solution ;)
$localizacao = [
'equipamento_id' => $id,
'centrocusto_id' => $input['centrocusto_id'],
'projeto' => $input['projeto'],
'data_movimentacao' => $input['data_movimentacao']
];
$this->localizacao->create($VLocal->all($localizacao));
I dont know if this is the best way to do it but works, but if somebody has the right way to do post please!
Are you using Laravel 5?
If yes, use form Requests, they make everything easier. If you need to validate two things from one form, you just put two requests in the controller method. I use this when I register an user for an ecommerce page. I need to validate the user data and the address data, like this:
public function store(UserRegisterRequest $user_request, AddressCreateRequest $add_request)
{
//if this is being executed, the input passed the validation tests...
$user = User::create(
//... some user input...
));
Address::create(array_merge(
$add_request->all(),
['user_id' => $user->id]
));
}}
Create the request using artisan: php artisan make:request SomethingRequest, it generates an empty request (note the authorize function always returns false, change this to true or code that verifies that the user is authorized to make that request).
Here's an example of a Request:
class AddressCreateRequest extends Request {
public function authorize()
{
return true;
}
public function rules()
{
return [
"fullname" => "required",
//other rules
];
}
}
More on that on the docs:
http://laravel.com/docs/5.0/validation#form-request-validation

Check if field exists in Input during validation using Laravel

I want to make sure that certain fields are posted as part of the form but I don;t mind if some are empty values.
The 'required' validation rule won't work as I am happy to accept empty strings. I have tried the below, but as the 'address2' field is never sent, the validator doesn't process it.
Any ideas?
$rules = array(
'address2' => 'attribute_exists'
);
class CustomValidator extends Illuminate\Validation\Validator {
public function validateAttributeExists($attribute, $value, $parameters)
{
return isset($this->data[$attribute]);
}
}
You can use Input::has('address2') to check if something is posted by address2 input name. See the example:
if(Input::has('address2')) {
// Do something!
}
In Laravel 5,
if($request->has('address2')){
// do stuff
}
You should make custom validator like this.
use Symfony\Component\Translation\TranslatorInterface;
class CustomValidator extends Illuminate\Validation\Validator {
public function __construct(TranslatorInterface $translator, $data, $rules, $messages = array())
{
parent::__construct($translator, $data, $rules, $messages);
$this->implicitRules[] = 'AttributeExists';
}
public function validateAttributeExists($attribute, $value, $parameters)
{
return isset($this->data[$attribute]);
}
}
This will make AttributeExists work without to use require. For more explain about this. When you want to create new validator rule. If you don't set it in $implicitRules, that method will not work out if you don't use require rule before it. You can find more info in laravel source code.
When you submit a form each and every field is posted, matter of fact is if you leave some filed empty then that field value is null or empty. Just check the POST parameters once, to do so open the firebug console in firefox and submit the form, then check the post parameters. As you want to accept empty string what is the use of any rule?
else You can do this
$addr2=Input::get('address2');
if(isset($addr2)){
//do here whatever you want
}else{
//do something else
$addr2='';//empty string
}
Actually, Laravel has a method to validate if an attribute exists even if not filled.
$rules = [
'something' => 'present'
];
All the validation rules are stored in Validator class (/vendor/laravel/framework/src/Illuminate/Validation/Validator.php), you can check for the implementation of each rule, even no documented rules.

Resources