Codeigniter check unique value when editing form without using callback function - validation

Codeigniter check unique value while editing form.
When edit the form it checks for current row, and it give username already exist. so how to avoid it.and don't check for current record.
So how can i pass id to is_unique function in CI_Form_Validation class function and add condition?
See my below code:
$this->custom_validation->set_rules('username','Username',
'trim|required|max_length[30]|is_unique[adminuser.username]');

Simply put a unique validation only if value of that field is changed ie.
$old_value='old value';
if ($posted_value!=$old_value) {
$this->custom_validation->set_rules('username','Username',
'trim|required|max_length[30]|is_unique[adminuser.username]');
} else {
$this->custom_validation->set_rules('username','Username',
'trim|required|max_length[30]);
}

Related

Validate if another field is empty laravel validation

I want to validate field if present and will fail if another field not present
How to do it ? I have create custom validation to get record based id on storage
I have field product_id and amount and the amount field validate between max and min based on product_id, if i present the amount = 100000 and not fill the product_id field the validating for amount field is passed and display error because i am not fill the product_id i want check before the custom validation execute will check if product_id empty or not..
I have read all validation method on laravel docs still didnt find the solution.
How to do it ?
Finally i found a solution...
on Form Request class i just add sometimes rule on validate instance so when the product_id field not present on amount field will not validate and when present it will validate using validation rules like this:
class StoreRequest extend FormRequest
{
protected function getValidatorInstance()
{
$validator = parent::getValidatorInstance();
$validator->sometimes('amount', 'required|numeric|max_amount:product_id', function ($input) {
return Arr::has($input, 'product_id');
});
return $validator;
}
}

Laravel unique validation must include appended text when validating

I am using the Laravel tenancy package in which there is a domains table in my database and each value in the domain column within this table is appended with .test.co.uk.
When the user enters the URL in the form, they are presented with an input element (shown above) in which they enter a URL/Domain but the .test.co.uk is already appended so the only thing they need to enter is the text that goes before that, e.g. they would enter johnsmith and in the domain column it would store johnsmith.test.co.uk. The problem I have is that I need the validation on this column to be unique but also include the .test.co.uk when performing the validation so that it looks at the value stored in the table because if a user enters johnsmith and there is currently a record in the domains table where the value is johnsmith.test.co.uk then the validation would pass but I need the validation to fail in this scenario. I am currently using a Request class which is extending the FormRequest class and have this:
public function rules()
{
return [
'url' => 'required|string|unique:domains,domain',
];
}
I have also tried a rule object but I don't think a rule object is the correct solution to this problem. Is there a convenient "Laravel" way of doing this?
In your Request class use prepareForValidation()
Docs: https://laravel.com/docs/7.x/validation#prepare-input-for-validation
protected function prepareForValidation()
{
$this->merge([
'url' => $this->url . '.test.co.uk',
]);
}

Yii2: How to avoid required fields in a view?

I have a view about holidays where a user uses a form to choose a place to travel and a hotel. It has two models: HolidaysPlaces and HolidaysHotels.
The user have to fill the form in this order using the view:
The user completes the fields called Place and City (related with the HolidaysPlaces model).
The user checked a checkbox if he/she wants to choose a hotel. It able a field called Hotel (related with HolidaysHotels model).
The user completes that field.
The user press a Create button.
The controller receives and saves both models.
But the problem is when the user doesn't select the checkbox (number 2 of the list): The Hotel fieldis still required (with the red asterisk as defined in its model file). So the Create button doesn't work in this case.
How can I disabled the required feature?
Add a scenario for this case in your HolidaysHotels model, and include only the fields that you want checked.
Example: If you have 3 fields name, date and age that are required, create a scenario for two only, and set the scenario in the controller. Only those two fields will be checked.
In model:
public function scenarios(){
$scenarios = parent::scenarios();
$scenarios['create'] = ['name', 'date'];
return $scenarios;
}
In controller:
$holiday = new HolidayHotels();
$holiday->scenario = 'create';
To know more about scenarios: http://www.yiiframework.com/doc-2.0/guide-structure-models.html#scenarios
You can add some condition based validation in your model rules. Here is the snippet for both client and server validation. You can many conditions inside the function block.
['field-1', 'required', 'when' => function ($model) {
return $model->check_box == '1';
}, 'whenClient' => "function (attribute, value) {
return $('#checkbox-id').is(':checked') ';
}"],
The easiest way to solve it is to send the model with empty strings. Then the controller checks if the strings are empty. If so, the model is not saved. Else, it is saved.
It was the only way that works for me.

Ignore empty form values on update using laravl5

Is there anyway to remove empty form value form request->all() method ?
This is what i am trying to do on update,In other words only post filled form values.
$data = request()->except(['_token','id']);
DB::table($table)->where('id',$id)->update($data);
Note:I have dynamically generated columns so i think i can't use those column in except parameters's list.
This updates all the column of the row,but all i want to update only those column that's value is filled and for the remaining columns/fields keep the same old value
Have a look at array_filter
// All posted data except token and id
$data = request()->except(['_token','id']);
// Remove empty array values from the data
$result = array_filter($data);
// update record
DB::table($table)->where('id', $arr)->update($result);
Hope this helps.
// app/controllers/GiftsController.php
public function update($id)
{
// Grab all the input passed in
$data = Input::all();
// Use Eloquent to grab the gift record that we want to update,
// referenced by the ID passed to the REST endpoint
$gift = Gift::find($id);
// Call fill on the gift and pass in the data
$gift->fill($data);
$gift->save();
}
I found this piece of code in this tutorial and works like charm. I hope it helps.

PasswordField validation in SilverStripe

I have a member in my project called Customer. I need to validate PasswordField.
I created a function in my page containing the PasswordField as below
function getValidator() {
$data = $this->loadData();
if (#$data['Password']->minLength(7)) {
return $this->validationError('Password', 'Password field should contain minimum 7 charactors', 'bad');
}
}
This does not give any result. How do I get this working?
Remove that ugly # from your code and watch that beautiful error message. Error supression is a real bad practice, you should avoid that
There is already a class PasswordValidator which is used by the Member object and can check the minimum length of a password. (See API Docs for PasswordValdiator)
If you show us more code I can try to help you implementing it right.
Is your Customer object a subclass of Member? Where is the password changed? What FormField is used for Password? There is also a ConfirmedPasswordField showing two masked fields for matching passwords where you can set a minlength.
So, assuming you save your password in a field called Password you could set up the field e.g.
$passwordField = ConfirmedPasswordField('Password', 'Choose a password');
$passwordField->minLength = 7; //there is no setter method for that right now
Then add $passwordField to your FieldList e.g using
$fields->push($passwordField);

Resources