How to validate input field against the database in Yii 2.0? - php

Suppose I have a field name id and I want the user to enter some integer in the id field but at the same time I want to check that id against the database whether it exists or not. If it exists then it should show some error.
Is there a function to achieve this in Yii 2.0?

If this is from a model, you can have a unique rule to it in the validation rules.
In your model, you have a rules() function:
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
return array(
array('name', 'required'),
array('some_id', 'unique'),
);
}

Related

Yii2 - Ignore validation if

In my Yii2 project, I have related models. Example: A model Customer would have an attribute address_id that relates to another model Address. In the Customer model have the exist validator that checks that the row exists in the address table.
Typically, on create or update, this validation is ignored if address = null. My problem is that sometimes FE would send the address = 0 indicating the absence of an address.
In this case, I need to not only ignore validation, but to set address = null. This can be done beforeSave of course, but I'm trying to check if there's some built-in way through which I can do this
You can use the filter validator for normalization of an input data. For example:
class Customer extends ActiveRecord
{
public function rules()
{
return [
['address_id', 'filter', 'filter' => function ($value) {
return $value == 0 ? null : $value;
}],
// other validators
];
}
}

yii2 user-defined validation of mobile number

i am new to Yii2. I want to validate mobile number by custom validation function. How can i validate mobile no in Yii2 and how can i use user-defined rule to yii2 and How can we add error message to any attribute in yii2 after form post? Thanks in advance
you need to edit your model. Lets say you have the following model:
class User extends ActiveRecord implements IdentityInterface
{
...
/**
* #inheritdoc
*/
public function rules()
{
return [
[['email', 'password', 'id'], 'required'],
[['email', 'username'], 'unique'],
['mobile', 'customValidation'] //<----this will be your custom validation
}
public function customValidation(){
//perform your validation here
if(/*has error*/){
$this->addError("mobile","Your mobile number is not valid.");
}
}
}
the addError method's first parameter is the atribute you want to add the error to and the second parameter is the message you want to show.
Hope this helps ;)
Maybe this could help anyone.
Use pattern match in Yii2 and validate your input field.
It's going to check and return alert message if number has less/more than 10 digits.
['mobile', 'match', 'pattern'=>"/^[0-9]{3}[0-9]{3}[0-9]{2}[0-9]{2}$/",'message'=> 'Not Correct Format - mobile number should have 10 digits.'],

How to ignore uniqueness for multiple fields

I have two models: Cities and Schools. As you already understand Cities can have many schools and taking this into account I have defined my model as follows:
class School extends Model
{
public $fillable = ['city_id' ,'name'];
public function city()
{
return $this->belongsTo('App\City','city_id','id');
}
}
class City extends Model
{
public $fillable = ['name'];
Public function schools()
{
return $this->hasMany('App\School', 'id','city_id');
}
}
But I have faced a pproblem when trying to validate update of a school model. I have to validate whether name of the school is unique for selected city or not. I have defined the rule like this:
$rules = array(
'name' => ['required', Rule::unique('schools')->ignore($id)],
);
$validator=Validator::make(Input::all(),$rules);
But it is not allowing to save a school with existing name in other city than selected. How should I change the rule to ensure that school names can be same if the city is different.
Thank you.
Custom rule
The best solution would be to create a custom rule for this, that accepts the field with the corresponding city name/id as a parameter.
Something like
//Calling the custom rule like this
['name' => 'required|validateSchool:yourFieldNameOfCityHere'];
Declaring the custom validation function in your service provider like this
Validator::extend('validateSchool', function ($attribute, $value, $parameters, $validator) {
$cityName = ($validator->data, $parameters[0]);
//Now check if the $value is already set for the specific city by using normal database queries and comparison
return count(City::whereName($cityName)->schools()->whereName($value)->get()) == 0
});
What does it
The custom validation rule receives the data of the field you give with the function (in the code above it's yourFieldNameOfCityHere), so it knows which city the user chose. With this information, you now can check if there is already a school with the name for the entered city.
At the DB level, it sounds like what you want is a compound uniqueness constraint across name and city_id. Eloquent seems to support passing an array of column names in model definitions. It seems like this requires custom validation, though. See Laravel 4: making a combination of values/columns unique and the custom validator at https://github.com/felixkiss/uniquewith-validator

Set custom validation message for field in laravel5 form validation?

I want to set custom filed name in laravel5 form validation error messages.
my form validation request class is,
class PasswordRequest extends Request {
protected $rules = [
'old' => ['required'],
'new' => ['required','same:cnew'],
'cnew' => ['required']
];
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize() {
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules() {
return $this->rules;
}
}
Here when old,new and cnew emty, Error message will be like following,
The old field is required.
The new field is required.
The cnew field is required.
I want to display like following instead of above message,
Old password field is required
New password field is required
Confirmation password field is required.
How it is possible in laravel5 Form Request Validation method?
Option 1:
You can define your custom attributes in resources/lang/en/validation.php under Custom Validation Attributes 'attributes' => [], like so:
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/
'attributes' => [
'old' =>'Old Paaword',
'new' =>'New password',
'cnew' =>'Confirmation password'
]

yii : $model->save() inserts null values when we I have empty rules

I don't have any rules for the input fields, (name,place, position) so my model's rules function returns an empty array, but then empty values are getting saved into the database table.
public function rules()
{
return array();
}
Also when I omit rules() function from my model
$model->save()
returns true but DB table get inserted with empty values.
so how can I omit rules() function from my model class ?
So you should set all of them as safe attribute in rules.
public function rules(){
return array
array('id, name, /*list attribute here*/', 'safe')
);
}
You have to define safe attribute in rules.
public function rules(){
return array(
array('id, name, place, postion', 'safe')
);
}
Key Point - Massive Assignment will only be made for fields which have passed some explicit validation rule.

Categories