Unable to change value with codeIgniter validation - php

Here i have a list of contacts where user can add new contacts as well as edit them. Now at the add time i'm using server-side validation by codeIgniter for reduce redundancies. Also here i have a number of users that can add their contacts.
Suppose their are users named "John" and "Sara".
In this case, whenever "john" add new contact that are prevoiusly added by him, then it can't be add as duplicate contact number.
But whenever "john" add new contact that are previously added by "Sara", them it can be add . but its unable to add because CodeIgniter form_validation check unique value with entire table data.
Here is my Controller Code
$this->form_validation->set_rules('customer_email','Email', 'trim|check_email[customer.customer_email.' .$userId. ']', array('check_email' => 'Email must be unique.'));
$this->session->set_flashdata('check_email','Mobile must be unique');
$this->form_validation->set_rules('customer_mobile', 'Mobile', 'required|is_unique[customer.customer_mobile]');
$this->session->set_flashdata('contact_exists','Mobile must be unique');
if ($this->form_validation->run()) {
$userdata = $this->session->userdata();
$userId = $userdata['id'];
if (!$userId):
redirect(site_url());
endif;
I trying to many time but unable to fix this issue. I need your kind efforts. Thanks

Please find below solution.
First you need to remove unique check from customer_mobile.
$this->form_validation->set_rules('customer_mobile', 'Mobile', 'trim|required');
Once form_validation runs true then check customer_mobile with user in database and if it return row then return error else insert Contact.
if ($this->form_validation->run() == TRUE) {
// $check = Check here for customer_mobile with user in database
if($check):
return 'Contact already exist';
else:
// Insert Contact
endif;
}
Let me know if it not works.

Related

Laravel admin update users' info, duplicate email entry when updating his own admin account information

I am working on a laravel 8 application and using spatie/laravel-permission for roles and permissions. On the admin page, I'm displaying all users which the admin can do CRUD operations on. The users list also includes his own admin account.
The problem I'm having is when updating user details. The admin can successfully update user account information for other users with validation. However, if the admin tries to edit the information of his own admin account, the validation passes but I get an SQL error :
Integrity constraint violation: 1062 Duplicate entry 'admin#email.com'
for key 'users_email_unique'
See below my UserController update method for updating user information with validation:
public function update(Request $request, User $user)
{
$edit_user_rules = array(
// ... other validation rules ...
//'email' => "required|email|unique:users,email,{{$user->id}}", //. auth()->user()->id,
'email' => ['required', 'string', 'email', Rule::unique('users')->ignore($user->id)],
// ... other validation rules ...
);
$validator = Validator::make($request->all(), $edit_user_rules);
if ($validator->fails()) {
Session::flash('failed', 'Failed to save User details!');
return redirect(route('editUser', ['user' => $user->id]))->withErrors($validator)->withInput();
} else {
$validated = $validator->validated();
$updatedUser = User::find($user)->first();
// ... other user fields ...
$updatedUser->username = $validated['username'];
$updatedUser->email = $validated['email'];
// ... other user fields ...
if ($updatedUser->save()) {
return redirect(route('allUsers'));
} else {
return redirect(route('allUsers')); // with errors
}
}
}
I've tried to use different validation rules on the email field, for example,
"required|email|unique:users,email,{{$user->id}}"
"required|email|unique:users,email," . auth()->user()->id
but none worked. So I used a validation Rule to validate the unique email field. It works fine when I try to update other users' information but I get the SQL duplicate email error when updating the admin's own account.
Would appreciate any help I can get
The error is getting passed the validation rules, but it's failing when it saves the rule. This is because you're not getting the user properly. find() automatically gets the first record, so first() is unneeded, and is actually probably pulling the wrong account. When I try User::find(3)->first() locally, I'm getting user 1 instead of user 3. Remove first() from your call.
$updatedUser = User::find($user->id);
You didn't determined which column should be unique to ignore him self.
Change your email validation line to :
'email' => ['required', 'email', Rule::unique('users', 'email')->ignore($user->id)],
Don't forget to put this like to top of your code use Illuminate\Validation\Rule; .

how to validate email exists in database using luman while create new user?

how to validate email exists in database using luman while create new user?.
my registration controller code
$borrower = borrowerRegistration::create($request->all());
$last_borrower_id=DB::getPdo()->lastInsertId();
$store_borrower_array=array();
$store_borrower_array["borrower_id"]=$last_borrower_id;
$borrower_result = array('status' => 'true','message' =>'The First step borrower registration successfully.','content'=>array('registration'=>$store_borrower_array));
return json_encode($borrower_result);
please give a valuable suggestions.
You can try this way. here User is your Model (I am assuming)
if (User::where('email', '=', Input::get('email'))->exists()) {
// user found
}
Replace Input::get('email') to your email address from where you are getting and storing it.

Codeigniter custom url string

I am new to codeigniter and i am working on making a doctors site and need to allow users to search for doctors using simple url like http://www.mywebsite.com/newyork .so this url doesn't have any class as there can be many states and cant have class for each state. Should i change 404 override in routes script? Or there is a better way to achieve it
$route['(:any)']='search/check_state';
if i use above routing then other page like /login doesnt work.Please help
Make database that contains all states and do it this way
Inside search/check_state
// Get state from URL
$state = $this->uri->segment(1, "");
// Make sure state is not null and its found in database
if($state <> "" && $this->validateState($state)){
// Valid state, continue
}else{
// Give error message / redirect to 404 page
}
Add new function to controller
function validateState($state){
// If database contains $state then return true else return false
}
UPDATE
You can also do it with POST form.
Make form into page where user gives input details
echo form_open(base_url().'path_to_post_validation');
// make form here that sends "state" into page that handles validation
echo form_close();
Handle POST validation
// Make sure user has send POST request
if($this->input->post()){
// Set form validation rules
$this->form_validation->set_rules('state', 'state', 'required|trim|xss_clean');
// Run form validation
if ($this->form_validation->run() == TRUE){
// Store state into variable
$state = $this->input->post('state');
// Check database that it contains $state and then continue or give error message
}
}
got it try
$route['search/check_state/:any'] ='search/check_state';

kohana validation during update

In my application developed using Kohana, I have a form where user enters their registration information, My rules are correctly executing and the error message is displaying correctly if user ignores an important field or enters an email address in inappropriate form.
The problem is that i want to do the same validations while an his personal information at a later point of time, but i want to ignore the password fields which is usually empty when the form loads.
Is it really possible to make kohana ignore the blank password values
while updating?
I am using the following code to update user data, I could see no
validation is performed(which is defined in my Model_User) when i use
update_user() of Auth. Can somebody please throw some light on
potential issues that hinders the execution of validation routines
here?
if(Auth::instance()->logged_in()) {
$values = array();
$now = new DateTime();
$userobj = Auth::instance()->get_user();
//$userobj->updatedon = $now->format('Y-m-d H:i:s'); // need research
try {
$userobj->update_user($_POST, array('email',
'password',
'firstname',
'secondname',
'lastname',
'phone',
'city_id'
));
$values = Auth::instance()->get_user()->as_array();
} catch (ORM_Validation_Exception $e) {
$errors = $e->errors('models');
}
//...
This shouldn't be a problem. When registering users, make sure to use create_user() and add password specific rules to get_password_validation().
Now the logic will only apply for registration and not for updating already existing users.
Also if you don't want to update the password, make sure to remove it from the list.
$updateColumns = array('email', 'password', ...);
if ( ! isSet($_POST['password']) || trim($_POST['password']) == "") {
unset($updateColumns[1]);
}
$userobj->update_user($_POST, $updateColumns);

Symfony 1.4 conditional validation

I have a Profile form that inherits from sfGuardRegisterForm
I have these fields:
$this->useFields(
array('first_name',
'last_name',
'email_address',
'country',
'language',
'current_password',
'new_password',
'password_again',
)
);
Required fields are:
email_address, country and language
And the conditions are:
If the email_address is not equal with the current email_address
then check if it's unique then save it
If the current_password is the actual password of the user then verify if new_password and password_again are equals and verify that the new_password is not equal to the actual password of the user
I just can't figure out in how implement this
EDIT
Thanks 1ed your example works but the problem is that I load the user Profile and I fill the fields: 'first_name', 'last_name', 'email_address', 'country', 'language' with the actual logged user so the email_address field will show the email address:
//...
$this->widgetSchema['email_address']->setDefault($this->_user->getEmailAddress());
//...
If the user dont change the email it will always show this message:
An object with the same "email_address" already exist.
I just want to skip that
Also this $this->getObject()->checkPassword() does not works, always show this message:
Incorrect current password.
I use:
$this->_user = sfContext::getInstance()->getUser()->getGuardUser();
To get actual user profile
EDIT2
Thanks again 1ed
This is very weird and I'm getting frustated, this is the situation
I have a "workaround" for this but it does not follow the standard, I can make it works but using sfContext::getInstance()->getUser()->getGuardUser(); and it will be more unnecesary code
If I use new ProfileForm($user) automatically fills all the fields, that's very good but I can't setDefault() I can't set null or empty any field so I can't use doUpdateObject() because this function only works when the current data is updated, also I have tested overriding bind(), save() etc. without results
email_address uniqueness: you should set unique: true in schema, in sfDoctrineGuardPlugin that's the case by default, so in BasesfGuardUserForm you should see a unique validator already: sfValidatorDoctrineUnique(array('model' => 'sfGuardUser', 'column' => array('email_address'))
current_password: you should create a callback type post validator for this
// in sfGuardRegisterForm::configure()
// these fields can be blank
$this->getValidator('current_password')->setOption('required', false);
$this->getValidator('new_password')->setOption('required', false);
$this->getValidator('password_again')->setOption('required', false);
// check the current password (this validator is not `required` by default)
$this->mergePostValidator(new sfValidatorCallback(array(
'callback' => array($this, 'checkPassword'),
), array(
'invalid' => 'Incorrect current password.'
)));
// add this method to the same form class
public function checkPassword(sfValidatorBase $validator, array $values, array $arguments)
{
// if a new password is given check whether the old one is correct or not and rise an error if not correct
if(0 != strlen($values['new_password']) && !$this->getObject()->checkPassword($values['current_password']))
{
throw new sfValidatorErrorSchema($validator, array(
'current_password' => new sfValidatorError($validator, 'invalid')
));
}
return $values;
}
Alternatively you can create a custom post validator, but I think it's not necessary.
EDIT:
If you would like to display empty email address just like the password fields add these to your form class:
// at form load remove the default value
protected function updateDefaultsFromObject()
{
parent::updateDefaultsFromObject();
if (isset($this['email_address']))
{
$this->setDefault('email_address', '');
}
}
// before save remove empty email address
protected function doUpdateObject($values)
{
if (isset($values['email_address']) && 0 == strlen($values['email_address']))
{
unset($values['email_address']);
}
parent::doUpdateObject($values);
}
I'll try and explain this in methodical terms instead of giving you a big block of code....
So first, you want to if (email_addr != current_email) and if that's true, go on to do
if (new_pass != current_pass) then follow on to make sure if (new_pass == new_pass_again)
Inside all of these IFs, you can return a true/false or some kind of flag, or just //do code inside the brackets :p
EDIT: encase these IFs in: if (country != NULL && language != NULL && email_addr != NULL)

Categories