I want to try to find a solution that it isn't possible to insert same number twice in a table or to turn red in case the number was inserted before.
See also bureautintdev.nl/question/example1
Use Laravels inbuild validator functionality.
$validator = Validator::make(array('phonenumber' => 'required|unique:users') );
// This will query DB for uniqueness of phone number in users table. Change according to your requirement.
//Check for validation
if($validator->fails()) {
$messages = $validator->messages();// get the error message.
return Redirect::to('inputview')->withErrors($validator);
}
else
{
//do your actual operation here.
}
In the "inputview", check for "phonenumber" error and do decorate your inputbox into red or raise alert.
#if ($errors->has('phonenumber')) <p>{{ $errors->first('phonenumber') }}</p> #endif //show error.
Related
By the way, this is not really a question. I just want really to share how to validate using a specific database in multiple database connections. Since I got this error and it took almost 2 days and thank you to the members of the Codeigniter 4 community who help me how to solve it.
I would like to share it also here for future references if someone encounters this error. Shout out to kenjis for the help!
At first, I thought it was just a bug in the codeigniter4 that if I have a multiple database connections the validation rules only use the default DB group. But unfortunately, No. I just don't specify what DB group I should verify.
In case you encounter this error, just add this on your controller:
protected function validate($rules, array $messages = []): bool
{
$this->validator = \Config\Services::validation();
// If you replace the $rules array with the name of the group
if (is_string($rules)) {
$validation = config('Validation');
// If the rule wasn't found in the \Config\Validation, we
// should throw an exception so the developer can find it.
if (! isset($validation->{$rules})) {
throw ValidationException::forRuleNotFound($rules);
}
// If no error message is defined, use the error message in the Config\Validation file
if (! $messages) {
$errorName = $rules . '_errors';
$messages = $validation->{$errorName} ?? [];
}
$rules = $validation->{$rules};
}
return $this->validator->withRequest($this->request)->setRules($rules, $messages)->run(null, null, 'other-db-group-name');
}
reference: https://github.com/codeigniter4/CodeIgniter4/issues/5654
My api receives an json object posted from my React app. The object has two properties, one holding an array of objects and the other holds an id number. Because the first array cannot be validated by Symfony's form validation, I have created an custom restraint for it.
$data = json_decode($request->getContent(), true);
$custom_constraint = new Assert\blah blah;
$errors = $validator->validate($data['datas'], $custom_constraint );
if (count($errors) > 0 ) {
$errorsString = (string) $errors;
return new JsonResponse(
[
'validation failed' => $errorsString
]);
}
This validation works by itself, but I also want to add the validation for the id number
$errors = $validator->validate($data['id'], new Assert\Type('integer'));
Now I have two results in the $errors object, how do I combine them into one error object that output errors for any one of them?
You should use AssertCollection. It's demonstrate here: How to Validate Raw Values
I have a form. When validation fails i redirect to the same page. "mobilepage1.blade.php"
But all my entries are all gone. I want all my entries to stay. Exept the password.
I redirect my page with View::make
return View::make('mobilepages.mobilepage1', array('errormessages' => 'errormessages'));
I use:
$input = Input::all();
to get the input.
All input
return Redirect::to('mobilepages')->withInput(Input::all());
Except password
return Redirect::to('mobilepages')->withInput(Input::except('password'));
Old Input
In your form view, use something like this for the inputs:
<?= Form::text('title', (Input::get('title') ?: NULL)); ?>
The (Input::get('title') ?: NULL) operator will return the previous title value if it was set and nothing if it wasn't set.
It should be done using something like this:
public formSubmitMethod() // Change formSubmitMethod with appropriate one
{
// This is the form submit handler
// Set rules and validate the inputs
$rules = array(...); // set rules here but there are other ways
$inputs = Input::except('_token'); // everything but _token
$validatior = Validator::make($input, $rules);
if($validatior->fails()) {
// Validation failed
return Redirect::back()->withInput()->withErrors($validatior);
}
else {
// Success
// Do whatever you want to do
}
}
In your form, use Input::old('fieldname'), something like this:
{{ Form::input('username', Input::old('fieldname')) }}
That's it, now if you redirect back for invalid user inputs then your form fields will be repopulated with old values. Don't use old() method in the password field. You can also access the error message for a field using something like {{ $errors->first('username') }}, so if this (username) field invalidated then the error message for this field will be printed out.
Also, notice that, to redirect back, I've use Redirect::back() not View::make(), it's (make) not for redirecting but for rendering a view to show it.
I have a list of User records that I'm saving at one time (the form is populated from an uploaded CSV).
Everything seems to be working fine, and my validation rules are being honoured, but one thing that's eluding me are the specific validation error messages.
I get the general validation error (if say, a field that is supposed to be unique is not), but I'm not getting an error on the specific field to let the user know what the actual problem is.
Is this a bug, or is there something wrong with my Code? Here's the action from my Controller (fwiw I'm passing the CSV data to this action from another action, hence the snippet at the beginning):
public function finalizeCsv() {
if ( isset($this->request->params['named']['csvData']) ) {
$csvData = unserialize( $this->request->params['named']['csvData'] );
} else {
$csvData = $this->request->data;
}
$this->set('users', $csvData);
if ($this->request->is('get')) {
$this->request->data = $csvData;
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->saveAll($this->request->data)) {
$this->Session->setFlash('Users added!', 'default', array('class' => 'success'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('There were errors with your data.');
}
}
}
For unique fields add a validation rule
'field_name' => array(
'rule' => 'isUnique',
'required' => 'create'
),
Next - when you get a error you will need to review $this->User->validationErrors. There will be many arrays inside - 1 for each created record. Loop through them, collect errors and send them to $this->Session->setFlash().
Also you better wrap $this->User->saveAll($this->request->data) into transaction if you're using InnoDB or other engine that supports transactions. On error - do rollback and try again.
$ds = $this->User->getDataSource();
$ds->begin();
// > saving here < //
$ds->commit(); //< on success
$ds->rollback(); //< on error
I'm building an admin utility for adding a bulk of images to an app I'm working on. I also need to to log certain properties that are associated with the images and then store it all into the database.
So basically the script looks into a folder, compares the contents of the folder to records in the database. All of the info must be entered in order for the database record to be complete, hence the form validation.
The validation is working, when there are no values entered it prompts the entry of the missing fields. However it happens even when the fields ARE filled.
I'm doing something a bit funny which may be the reason.
Because I'm adding a bulk of images I'm creating the data within a for loop and adding the validation rules within the same for loop.
Here is the results:
http://s75151.gridserver.com/CI_staging/index.php/admin_panel/bulk_emo_update
Right now I have default test values in the form while testing validation. The submit button is way at the bottom. I'm printing POST variable for testing purposes.
Here is the code:
function bulk_emo_update() {
$img_folder_location = 'img/moodtracker/emos/';//set an image path
$emo_files = $this->mood_model->get_emo_images('*.{png,jpg,jpeg,gif}', $img_folder_location); //grab files from folder
$emo_records = $this->mood_model->get_all_emos(); //grab records from db
$i=1; //sets a counter to be referenced in the form
$temp_emo_info = array(); //temp vairable for holding emo data that will be sent to the form
//loop through all the files in the designated folder
foreach($emo_files as $file) {
$file_path = $img_folder_location.$file;//builds the path out of the flder location and the file name
//loops through all the database reocrds for the pupose of checking to see if the image file is preasent in the record
foreach($emo_records as $record) {
//compairs file paths, if they are the
if($record->picture_url != $file_path) {
//FORM VALIDATION STUFF:
$rules['segment_radio['.$i.']'] = "required";
$rules['emo_name_text_feild['.$i.']'] = "required";
//populating the temp array which will be used to construct the form
$temp_emo_info[$i]['path'] = $file_path;
$temp_emo_info[$i]['name'] = $file;
}
}
$i++;
}
//sets the reference to validation rules
$this->validation->set_rules($rules);
//checks to see if the form has all it's required fields
if ($this->validation->run() == FALSE) { //if validation fails:
print_r($_POST);
//prepairs the data array to pass into the view to build the form
$data['title'] = 'Bulk Emo Update';
$data['intro_text'] = 'fill out all fields below. hit submit when finished';
$data['emos_info'] = $temp_emo_info;
$this->load->view('admin_bulk_emo_update_view',$data);
} else { // if it succeeds:
//printing for test purposes
print_r($_POST);
$this->load->view('form_result');
}
}
I'm new to codeigniter and php in general so if anything looks outrageously weird please tell me, don't worry about my feelings I've got thick skin.
if ($this->validation->run() == FALSE)
if you are calling the run() method of the validation class every time the script is run, will it ever return TRUE and run the else? Maybe a different return?
I'm a little cornfused by what's going on. Generally, if I'm having a problem like this, I will figure out a way to force the result I'm looking for. e.g. in your code, I'd force that else to run... once I get it to run, break down what happened to make it run. Rudimentary, but it has served me well.
You use array of rules in
$this->form_validation->set_rules()
wrong.
If you want to pass the rules in array you must stick to the key names like described here http://codeigniter.com/user_guide/libraries/form_validation.html#validationrulesasarray
So instead of
$rules['input_name'] = "required"
try this:
array(
'field' => 'input_name',
'label' => 'Name that you output in error message',
'rules' => 'required'
)