Validating Forms - php

I have a form that I submit with jQuery ajax and have it being sent to a controller function called submit to validate and do any other tasks I need to with the form data. I'm trying to find out why my form validation library isn't showing an error when the username doesn't contain only lowercase letters and numbers.
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|strtolower');
POST Value after form submission:
username TestingUSER
EDIT:
As far as I know it gets to the php server side properly.
PHP:
public function submit()
{
$output_status = 'Notice';
$output_title = 'Not Processed';
$output_message = 'The request was unprocessed!';
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|strtolower');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
$this->form_validation->set_rules('remember', 'Remember Me', 'trim|xss_clean|integer');
if ($this->form_validation->run() == TRUE)
{
}
else
{
$output_status = 'Error';
$output_title = 'Form Not Validated';
$output_message = validation_errors();
}
echo json_encode(array('output_status' => $output_status, 'output_title' => $output_title, 'output_message' => $output_message));
}
EDIT 2:
Based off of Sheikh answer. I am getting a response back that says "Unable to access an error message corresponding to your field name." It does say Form Not Validated for the title so the message isn't working.
public function check_username($str)
{
if (preg_match('#[0-9]#', $str) && preg_match('#[a-z]#', $str))
{
return TRUE;
}
$this->form_validation->set_message('username', 'This is not have an accepted value!');
return FALSE;
}
EDIT 3:
What I'm wanting to do is have it report back that there there are validation errors but not the specific errors in the pnotify response. However I do want it to display the specific errors under the form elements.
jQuery Code:
http://pastebin.com/1KehMJkh
Login Form:
http://pastebin.com/EfpBfbfN

I think you can use a callback function in your controller
public function check_username($str)
{
if (preg_match('#[a-z0-9]#', $str)) {
return TRUE;
}
$this->form_validation->set_message('check_username', 'This is not have an accepted value!');
return FALSE;
}
Validation rules for username
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|callback_check_username');
You may like this too.

Related

Unable to access an error message corresponding to your field name in CI3

I have checked all the possible things that might go wrong with my code but still it showing me this error. Please help .
Unable to access an error message corresponding to your field name Username.(check_username)
And this is my code below:
public function index()
{
if ( ! file_exists(APPPATH.'/views/login.php'))
{
/* Whoops, we don't have a page for that! */
show_404();
}
$this->load->helper('security');
$this->load->library('form_validation'); // Including Validation Library.
$this->form_validation->set_error_delimiters('<div class="error">', '</div>'); // Displaying Errors in Div
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|callback_check_username'); // Validation for Username Field
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean'); // Validation for Password field.
if ($this->form_validation->run() == FALSE) {
$this->load->view('login');
}
function check_username($username)
{
if ($username == 'test') {
$this->form_validation->set_message('check_username','already exists.');
return false;
} else {
return TRUE;
}
}
}
Do $config['global_xss_filtering'] = TRUE; in config file.
in Codeigniter-3 xss_filtering is not a part of form_validation.
You have to add the validation language in the system folder. Check the video
https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=6&cad=rja&uact=8&sqi=2&ved=0ahUKEwi71dGkn73MAhVBQI4KHeZJC2gQtwIIPTAF&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D56EDSocDhjk&usg=AFQjCNE_nhBpNwUOz9nkrcRYYgL50p34Kw&sig2=PSUISbtldDaWWdTyKJ6CPw&bvm=bv.121070826,d.c2E

Display flashdata message in codeigniter callback function

I've this registration function and the related callback to check if an username already exists in the database. It works all perfectly, but I have problems with flashdata message
Here's the code:
/*
* Checks registration
*/
public function verify(){
$this->form_validation->set_rules('nome', 'Nome', 'trim|required|min_length[2]|xss_clean');
$this->form_validation->set_rules('cognome', 'Cognome', 'trim|required|min_length[2]|xss_clean');
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]|xss_clean|callback_check_username');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('password_conf', 'Password Confirmation', 'trim|required|matches[password]');
if($this->form_validation->run() == FALSE)
{
$this->session->set_flashdata('error_reg', 'Something goes wrong, please check your registration form');
redirect('registration');
}
else
{
$this->registration_m->add_user();
$this->session->set_flashdata('success_reg', 'Registration Successful!');
redirect('registration');
}
}
public function check_username($username){
$result = $this->registration_m->check_username_m($username);
if ($result) {
$this->session->set_flashdata('username', 'Username già in uso, riprovare.');
return false;
} else {
return true;
}
}
As you can see there's a redirect on the function verify(), and the flashdata before is correctly shown in case of errors.
My Question is: is there a way to show (in case of error) the flashdata inside the callback function without changing the logic of this piece of code?
Hope I was clear at all, cheers.
Modify your code as below
public function check_username($username){
$result = $this->registration_m->check_username_m($username);
if ($result) {
$this->form_validation->set_message('check_username', 'The %s field can not be the empty');
return false;
} else {
return true;
}
}
See differences in code
$this->session->set_flashdata('username', 'Username già in uso, riprovare.');
$this->form_validation->set_message('check_username', 'The %s field can not be the empty');

Codeigniter : Resetting the form values

In my view, what I want to do is clear the form fields once the user has been successfully registered. Everything works fine here i.e. the user is being registered, success message is being shown to the user except that what I want to do is the clear the values of the form fields, for which I am using this
// Clear the form validation field data, so that it doesn't show up in the forms
$this->form_validation->_field_data = array();
After I added this, CI keeps giving me this error:
Fatal error: Cannot access protected property CI_Form_validation::$_field_data in
C:\wamp\www\CodeIgniter\application\controllers\user.php on line 92
Here is the relevent controller code:
public function signup()
{
// If the user is logged in, don't allow him to view this page.
if (($this->_isLoggedIn()) === true) {
$this->dashboard();
}
else
{
$data['page'] = 'signup';
$data['heading'] = 'Register yourself';
$data['message'] = $this->_regmsg;
$this->load->library('form_validation');
// $this->form_validation->set_rules('is_unique', 'Sorry! This %s has already been taken. Please chose a different one.');
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|is_unique[users.username]|callback_valid_username');
$this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
// run will return true if and only if we have applied some rule all the rules and all of them are satisfied
if ($this->form_validation->run() == false) {
$data['errors'] = isset($_POST['submit']) ? true : false;
$data['success'] = false;
$this->_load_signup_page($data);
}
else{
if($this->users->register_user($_POST)){
$data['errors'] = false;
$data['success'] = true;
// Clear the form validation field data, so that it doesn't show up in the forms
$this->form_validation->_field_data = array();
$this->_load_signup_page($data);
}
}
}
}
private _load_signup_page($data){
$this->load->view('template/main_template_head');
$this->load->view('template/blue_unit', $data);
$this->load->view('signup', $data);
$this->load->view('template/main_template_foot');
}
Can anyone please tell me what's the deal with this line?
$this->form_validation->_field_data = array();
P.S: Here is how I am showing the values in the form:
<?php echo set_value('fieldname'); ?>
It means this is a protected property and you can not use it directly. Instead of this you can do it simply like this
if($this->users->register_user($_POST)){
$data['errors'] = false;
$data['success'] = true;
unset($_POST)
$this->_load_signup_page($data);
}
This way is not recommended. Instead if you redirect to the same controller the form will reset itself automatically.
if($this->users->register_user($_POST)){
$data['errors'] = false;
$data['success'] = true;
redirect('controllername/signup');
}
Still if you need success messages you can use flash data for this. Here

CodeIgniter form validation valid_email not working

I am trying to use CodeIgniter's form validation class. I've used the "valid_email" parameter, as can be seen from the code below, but even when an invalid email address is entered it still passes the validation check. I tested with the string: testing123
public function login()
{
$this->form_validation->set_rules('authEmail', 'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('authPassword', 'trim|required');
$email = $this->input->post('authEmail');
$password = $this->input->post('authPassword');
if($this->form_validation->run() === FALSE) {
$this->session->set_flashdata('formValidationError', validation_errors('<p class="error">', '</p>'));
redirect('/');
} else {
// Begin authentication
}
}
Anyone have any idea what I'm doing wrong or if this is a CodeIgniter issue?
To note, I am setting a flashdata session as opposed to using:
<?php echo validation_errors(); ?>
... this is because I am doing a redirect back to the homepage (which is the login page as it's a private site).
Try this:
public function login()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('authEmail', 'Email', 'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('authPassword', 'Password', 'trim|required');
if($this->form_validation->run() !== false){
//validation passed
$email = $this->input->post('authEmail');
$password = $this->input->post('authPassword');
// Begin authentication
}
else {
$this->session->set_flashdata('formValidationError', validation_errors('<p class="error">', '</p>'));
redirect('/');
}
}
I'm just learning to use it as well, but don't you need three parameters? This is from their form validation page:
$this->form_validation->set_rules('email', 'Email', 'required');
From http://codeigniter.com/user_guide/libraries/form_validation.html#validationrules
The field name - the exact name you've given the form field.
A "human" name for this field, which will be inserted into the error message. For example, if your field is named "user" you might give it a human name of "Username". Note: If you would like the field name to be stored in a language file, please see Translating Field Names.
The validation rules for this form field.

Codeigniter form validation error message

I have a form on my website header where i allow the user to log in with his username/password... then i POST to /signin page and check if the username exists to allow the user to log in.. if there is a problem upon login i output these errors...
i tried using the following code to show a custom error but with no luck
if ($this->form_validation->run() == false){
$this->load->view("login/index", $data);
}else{
$return = $this->_submitLogin();
if ($return == true){
//success
}else{
$this->form_validation->set_message('new_error', 'error goes here');
//error
}
$this->load->view("login/index", $data);
}
how does set_message work and if this is the wrong method, which one allow me to show a custom error in this case?
EDIT :
validation rules:
private $validation_rules = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'trim|required|callback__check_valid_username|min_length[6]|max_length[20]|xss_clean'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|min_length[6]|max_length[32]'
),
);
The set_message method allows you to set your own error messages on the fly. But one thing you should notice is that the key name has to match the function name that it corresponds to.
If you need to modify your custom rule, which is _check_valid_username, you can do so by perform set_message within this function:
function _check_valid_username($str)
{
// Your validation code
// ...
// Put this in condition where you want to return FALSE
$this->form_validation->set_message('_check_valid_username', 'Error Message');
//
}
If you want to change the default error message for a specific rule, you can do so by invoking set_message with the first parameter as the rule name and the second parameter as your custom error. E.g., if you want to change the required error :
$this->form_validation->set_message('required', 'Oops this %s is required');
If by any chance you need to change the language instead of the error statement itself, create your own form_validation_lang.php and put it into the proper language folder inside your system language directory.
As you can see here, you can display the custom error in your view in the following way:
<?php echo form_error('new_error'); ?>
PS: If this isn't your problem, post your corresponding view code and any other error message that you're getting.
The problem is that your form is already validated in your IF part! You can fix the problem by this way:
if ($this->form_validation->run() == false){
$this->load->view("login/index", $data);
}else{
$return = $this->_submitLogin();
if ($return == true){
//success
}else{
$data['error'] = 'Your error message here';
//error
}
$this->load->view("login/index", $data);
}
In the view:
echo $error;
The CI way to check user credentials is to use callbacks:
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
...
public function username_check($str) {
// your code here
}
I recommend you to read CI documentation: http://codeigniter.com/user_guide/libraries/form_validation.html
The way I did this was to add another validation rule and run the validation again. That way, I could keep the validation error display in the view consistent.
The following code is an edited excerpt from my working code.
public function login() {
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$data['content'] = 'login';
if($this->form_validation->run()) {
$sql = "select * from users where email = ? and password = ?";
$query = $this->db->query($sql, array($this->input->post('email'), $this->input->post('password')));
if($query->num_rows()==0) {
// user not found
$this->form_validation->set_rules('account', 'Account', 'callback__noaccount');
$this->form_validation->run();
$this->load->view('template', $data);
} else {
$this->session->set_userdata('userid', $query->id);
redirect('/home');
}
} else {
$this->load->view('template', $data);
}
}
public function _noaccount() {
$this->form_validation->set_message('_noaccount', 'Account must exist');
return FALSE;
}
Require Codeigniter 3.0
Using callback_ method;
class My_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->form_validation->set_message('date_control', '%s Date Special Error');
}
public function date_control($val, $field) { // for special validate
if (preg_match("/^[0-9]{2}.[0-9]{2}.[0-9]{4}$/", $val)) {
return true;
} else {
return false;
}
}
public function my_controller_test() {
if ($this->input->post()) {
$this->form_validation->set_rules('date_field', 'Date Field', 'trim|callback_date_control[date_field]|xss_clean');
if ($this->form_validation->run() == FALSE) {
$data['errors']=validation_errors();
$this->load->view('my_view',$data);
}
}
}
}
Result:
if date = '14.07.2017' no error
if date = '14-7-2017' Date Field Date Special Error

Categories