CodeIgniter form validation, show errors in order - php

Lets say I have a login form and it has fields username and password. Both of the fields are required to be filled in and when you submit the form it has two different lines for them.
Username field is required.
Password field is required.
What I want to do is to show only the username field errors and when they don't have any errors with username field, it will show the password field errors.
How would this be done?
Also, I remember there is a way to show errors only regarding a field, what was the snippet for it?

I suggest using a custom callback function tied to just one input, that checks both inputs and conditionally sets the desired message.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class YourController extends CI_Controller {
public function save()
{
//.... Your controller method called on submit
$this->load->library('form_validation');
// Build validation rules array
$validation_rules = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'trim|xss_clean|callback_required_inputs'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|xss_clean'
)
);
$this->form_validation->set_rules($validation_rules);
$valid = $this->form_validation->run();
// Handle $valid success (true) or failure (false)
if($valid)
{
//
}
else
{
//
}
}
public function required_inputs()
{
if( ! $this->input->post('username'))
{
$this->form_validation->set_message('required_inputs', 'The Username field is required');
return FALSE;
}
else if ($this->input->post('username') AND ! $this->input->post('password'))
{
$this->form_validation->set_message('required_inputs', 'The Password field is required');
return FALSE;
}
return TRUE;
}
}

Related

how to make confirm password validation cakephp with hashing it

I'm using cakephp 2.xx, I want to hashing password with sha256 before it going to database,
before it I wanna make validation value password in my form input, validation which check password input and re-confirm password is match, if In my controller, when form catch validation, the password automatically hash
if ($this->request->data['Driver']['password'] != $this->request->data['Driver']['confirm_password']) {
$this->request->data['Driver']['password'] = hash('sha256',$this->request->data['Driver']['password']);
}
necessarily, the password hash when form no catch validate at all, so how can I make validation in my model ?
Thanks In Advance.
In your model (Driver.php)
Validation
<?php
public $validate = array(
'password' => array(
'notempty' => array(
'rule' => array('notempty'),
),
'password_confirm'=>array(
'rule'=>array('password_confirm'),
'message'=>'Password Confirmation must match Password',
),
),
);
?>
Custom validation rule
<?php
public function password_confirm(){
if ($this->data['Driver']['password'] !== $this->data['Driver']['password_confirmation']){
return false;
}
return true;
}
?>
Hashing,but I think that better to choose AuthComponent
<?php
public function beforeSave($options = array()) {
$this->data['Driver']['password'] = hash('sha256',$this->data['Driver']['password']);
return true;
}
?>
It's overall description and you probably would need to modify some parts of it

Can one use inline validation rules, and config file based validation rules simultaneously?

PHP / CodeIgniter.
In order to set up a form that validates the logic: "either one, or both, of the fields is required" I have to use inline form validation like this (source is http://ellislab.com/forums/viewthread/136417/#672903):
if ( ! $this->input->post('email'))
{
$this->form_validation->set_rules('phone', 'Phone Number', 'required');
}
else
{
$this->form_validation->set_rules('phone', 'Phone Number', '');
}
// If no phone number, email is required
if ( ! $this->input->post('phone'))
{
$this->form_validation->set_rules('email', 'Email Address', 'required|valid_email');
}
else
{
$this->form_validation->set_rules('email', 'Email Address', 'valid_email');
}
But I have a whole lot of other forms where I'd prefer to use config file based form validation.
I cannot think of a way to get the two to co-exist, and I don't really want to now go and bring all my rules into the code body.
Any suggestions?
You can use rule sets from the config file or inline rules just fine in the same application.
config/form_validation.php
$config = array(
'ruleset1' => array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required|trim|alpha'
),
)
);
controller example
public function ruleset()
{
if ($this->input->post())
{
// runs validation using ruleset1 from the config
if ($this->form_validation->run('ruleset1') == FALSE)
{
...
}
}
}
public function inline_rules()
{
if ($this->input->post())
{
// ignores the config and uses the inline rules
$this->form_validation->set_rules('username', 'Username', 'required|trim|alpha_numeric');
if ($this->form_validation->run() == FALSE)
{
...
}
}
}
Note: I found that trying to mix them for the same form does not work. Specifying inline rules and a ruleset on the same form will cause the ruleset to be ignored completely and the inline rules to be applied.
Create a file in your libraries name it MY_Form_validation
class MY_Form_validation extends CI_Form_validation
{
public function __construct($rules = array())
{
parent::__construct($rules);
$this->CI->lang->load('MY_form_validation');
}
function email_phone($str)
{
if(!$str)
{
// if POST phone exists validate the phone entries
//validation for phone
return TRUE;
}else{
//if no phone was entered
//check the email
$email = $this->input->post('email'));
//use the systems built in validation for the email
//set your error message here
return $this->valid_email($email) && $this->required($email);
}
}
}
//or set the message here
$this->form_validation->set_message('email_phone','Please enter either an email or phone.');
$this->form_validation->set_rules('phone', 'Phone Number', 'email_phone');

How can I add an error message to a form?

I am validating a user login and would like to attach an error message to the form if they the user submits details that do not authenticate.
In FieldSet I can see function setMessages() but this only appears to match and set against an element key.
How can I attach an error message to the form and not to a form element?
The following code is in within the LoginForm class.
public function isValid()
{
$isValid = parent::isValid();
if ($isValid)
{
if ($this->getMapper())
{
$formData = $this->getData();
$isValid = $this->getMapper()->ValidateUandP($formData['userName'], $formData['password']);
}
else
{
// The following is invalid code but demonstrates my intentions
$this->addErrorMessage("Incorrect username and password combination");
}
}
return $isValid;
}
The first example is validating from a database and simply sending back an error message to the form:
//Add this on the action where the form is processed
if (!$result->isValid()) {
$this->renderLoginForm($form, 'Invalid Credentials');
return;
}
This next one is adding simple validation to the form itself:
//If no password is entered then the form will display a warning (there is probably a way of changing what the warning says too, should be easy to find on google :)
$this->addElement('password', 'password', array(
'label' => 'Password: ',
'required' => true,
));
I hope this is of use.
In ZF1: in order to attach an error message to a form - you can create a decorator element for this:
Taken from:
http://mwop.net/blog/165-Login-and-Authentication-with-Zend-Framework.html
class LoginForm extends Zend_Form
{
public function init()
{
// Other Elements ...
// We want to display a 'failed authentication' message if necessary;
// we'll do that with the form 'description', so we need to add that
// decorator.
$this->setDecorators(array(
'FormElements',
array('HtmlTag', array('tag' => 'dl', 'class' => 'zend_form')),
array('Description', array('placement' => 'prepend')),
'Form'
));
}
}
And then as an example in your controller:
// Get our authentication adapter and check credentials
$adapter = $this->getAuthAdapter($form->getValues());
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($adapter);
if (!$result->isValid()) {
// Invalid credentials
$form->setDescription('Invalid credentials provided');
$this->view->form = $form;
return $this->render('index'); // re-render the login form
}
Unsure if this still works in ZF2

Custom validation rule in CakePHP

I'm trying to create a custom validation rule for when a checkbox is checked, an input field will need to be filled out in order to proceed to the next page. If unchecked, the input field will not be required.
Here's my code in View:
echo $this->Form->inputs(array(
'legend'=>'Certifications',
'rn_box'=>array(
'type'=>'checkbox',
'label'=>'RN',
'value' => $results['Education']['rn_box']
),
'rn_number'=>array(
'label'=>'RN Number:',
'value' => $results['Education']['rn_number']
),
));
In my Model I created a function:
public function rnCheck () {
if ($this->data['Education']['rn_box'] == '0') {
return false;
}
return true;
}
public $validate = array(
'rn_number' => array(
'rnCheck'=>array(
'rule'=>'rnCheck',
'message'=>'Please Provide a Number'
),
),
);
The checkbox returns a value of 1 if checked, and a value of 0 unchecked. The rn_number field is an input field that I'm trying to validate. I tried playing with 'required', 'allowEmpty', etc. with no luck. If anyone can point me in the right direct, that would be great, thanks!
You can probably just handle it all in the function callback for rn_number. I would also call the function and rule name rn_number to avoid any confusion.
For example, change your validate array to:
public $validate = array(
'rn_number' => array(
'rn_number'=>array(
'rule'=>'rn_number'
),
),
);
And then your custom validation function can look like:
public function rn_number () {
if ($this->data['Education']['rn_box'] == 1) {
if($this->data['Education']['rn_number'] == '')
$errors[] = "Please enter your RN Number.";
}
if (!empty($errors))
return implode("\n", $errors);
return true;
}
I'm handling the error message in the custom validation function - not in the validate array. Let me know if this doesn't work!

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