Stop form validating on first error codeigniter - php

I'm using CI 3.1.7 and want to stop validating form if there is an error. For example:
$config = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required',
'errors' => array(
'required' => '%s is required',
),
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required',
'errors' => array(
'required' => '%s is required',
),
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required',
'errors' => array(
'required' => '%s is required',
),
)
);
When user leaves username and email blank, the form will show only username is required. Any help is appreciated, thank you!

You cannot stop validation->run() but you can control which error message displays. The limitation is you cannot show the error next to the related field. Or, I should say instead, I cannot think of an easy way to show the error next to the input it belongs to.
Anyway, here's how to extract the first error message.
if($this->form_validation->run() == FALSE)
{
$errors = $this->form_validation->error_array();
// There could be many but grab only the first
$fields = array_keys($errors);
$err_msg = $errors[$fields[0]];
}
If you want the name of the field you can use this.
$err_field = $fields[0];

If i got your question right .. you want to stop on the first encountered form validation error then you have to edit the core form validation library which is extremely bad practice but luckily you can extend its functionality and either edit the run() method itself or create your own method and just copy the run() code and edit this block of code:
// Execute validation rules
foreach ($this->_field_data as $field => &$row)
{
// Don't try to validate if we have no rules set
if (empty($row['rules']))
{
continue;
}
$this->_execute($row, $row['rules'], $row['postdata']);
// here is the modification
if(count($this->_error_array) > 0) return true; // error found
}
now it will stop execution when finding its first error

Pleas check
public function __construct()
{
parent::__construct();
// load form and url helpers
$this->load->helper(array('form', 'url'));
// load form_validation library
$this->load->library('form_validation');
}
Or check https://code.tutsplus.com/tutorials/codeigniter-form-validation-from-start-to-finish--cms-28768

Related

Validating Top Level Domains with Zend 1

I am having a problem with Validating Top Level Domains. Basically, anything with .tech as the TLD is failing the email validation.
I have inherited this project and don't know Zend very well but I have traced the problem back to the hostname not being valid here is the code on GitHub;
// Match hostname part
if ($this->_options['domain']) {
$hostname = $this->_validateHostnamePart();
}
$local = $this->_validateLocalPart();
// If both parts valid, return true
if ($local && $length) {
if (($this->_options['domain'] && $hostname) || !$this->_options['domain']) {
return true;
}
}
return false;
Now, I have some local code here;
class Form_InviteToSpaceForm extends Twitter_Bootstrap_Form_Horizontal
{
public function init()
{
// Set the method for the display form to POST
$this->setMethod('post');
$this->setAction('/team');
$this->addElement('textarea', 'email', array(
'label' => 'Email addresses',
'dimension' => 10,
'required' => true,
'placeholder' => "person1#email.com person2#email.com",//line breaks don't work on placeholders, have to force line wrap with spaces
'filters' => array('StringTrim'),
'validators' => array(
array('validator' => 'NotEmpty'),
array('validator' => 'EmailAddress', 'options' => array('messages' => array('emailAddressInvalidFormat' => 'Incorrect email address specified.')))
)
));
If I comment out the line with the last array('messages' => array('emailAddressInvalidFormat' => 'Incorrect email address specified.'))) then this whole validation is avoided. But I don't want to avoid using this. I just want to be able to extend and add .tech or whatever else comes up from genuine clients. How can I do this with Zend?
You can write custom validator extended from Zend validator
class My_Validate_Hostname extends Zend_Validate_Hostname
{
public function __construct($options = array())
{
parent::__construct($options);
$this->_validTlds = array_merge($this->_validTlds, array('tech'));
}
}
and pass it to email validator
$emailValidator = new Zend_Validate_EmailAddress(array('messages' => array('emailAddressInvalidFormat' => 'Incorrect email address specified.')));
$emailValidator->setHostnameValidator(new My_Validate_Hostname());
....
$this->addElement('textarea', 'email', array(
'label' => 'Email addresses',
'dimension' => 10,
'required' => true,
'placeholder' => "person1#email.com person2#email.com",//line breaks don't work on placeholders, have to force line wrap with spaces
'filters' => array('StringTrim'),
'validators' => array(
array('validator' => 'NotEmpty'),
)
))->addValidator($emailValidator);

Error message from form validation using a model method for custom rule

I need to display an error message for a custom validation rule, but I can't get to do it.
This is the validation rule:
$config = array(
....,
array(
'field' => 'general_sales_subaccount',
'label' => 'General Sales Subaccount',
'rules' => array(
'required',
'numeric',
array(
$this->subaccounts_model,
'is_valid'
)
),
)
);
$this->form_validation->set_rules($config);
And now this is the referenced model method:
public function is_valid($subaccount)
{
$subaccount_num_digits = $this->preferences->get('subaccount_num_digits');
if (strlen($subaccount) != $subaccount_num_digits ) {
$this->form_validation->set_message('is_valid', "The number of digits in %s doesn't match the length set to " . $subaccount_num_digits);
return false;
}
return true;
}
The rule seems to work, but it displays this error message:
Unable to access an error message corresponding to your field name (Anonymous function).
Any ideas?
You can't get an error message because you don't setup functions name. You may change your rule function like below:
$config = array(
....,
array(
'field' => 'general_sales_subaccount',
'label' => 'General Sales Subaccount',
'rules' => array(
'required',
'numeric',
array( //you may get all in another array
'is_valid', // and tell codeigniter your functions name
array(
$this->subaccounts_model,
'is_valid'
)
)
),
)
);
$this->form_validation->set_rules($config);

codeigniter form validation on array not form submit

i want validate my form input field or you want to say i have an array and i want to validate that array using codeigniter
Example :
i have array like :
$array['obj_type']='sample';
$array['obj_id']='44';
$array['user_id']='34566';
and my form validation config as like :
'validatedata' => array(
array(
'field' => 'obj_type',
'label' => 'No Type Define here',
'rules' => 'required'
),
array(
'field' => 'obj_id',
'label' => 'No any item selected here',
'rules' => 'required|is_natural_no_zero'
),
array(
'field' => 'user_id',
'label' => 'No user logged in',
'rules' => 'required|is_natural_no_zero'
),
),
and when i use form validate its not validate array
if ($this->form_validation->run('validatedata')) {
} else {
echo validation_errors();
}
its print all error which define on on validatedata config array;
i just use
$this->form_validation->set_data($array);
then i validate form
if ($this->form_validation->run('validatedata')) {
echo "sucess";
} else {
echo validation_errors();
}
now its works fine and good.
You have to load form validation library in your controller..
$this->load->library(array('form_validation'));
You have to provide the data to the form_validation library:
$this->form_validation->set_data($array);
and then you can use
$this->form_validation->run('validatedata')
as intended.
If you want to validate multiple arrays, you'll have to call reset_validation() after validating each array.
Check system/libraries/Form_validation.php (around line 255, depending on your version of CI) for more information.

Codeigntier validation issue while using tank_auth

So I have a code here to validate the usernname exist or not, I'm using tank_auth library
if(! $this->tank_auth->is_username_available($username))
{
$this->form_validation->set_message('username_check');
}
In the form validation file ( validation.php ) how can I call this message
'register_view' => array(
array(
'field' => 'username',
'label' => 'أسم المستخدم',
'rules' => 'required|trim|max_length[20]|username_check'
),
I added username_check at the end isn't this right?
well it's easier to use
'rules' => 'required|trim|max_length[20]|is_unique[users.username]'
Form validation
and add your custom message here
$this->form_validation->set_message('is_unique', 'Error Message');
I can see you are using Arabic it's better to check how to integrate language with default form validation messages as well

Zend framework - form not rendering

I'm just starting to use Zend Framework and was following the quick start documentation for the latest version (1.11.10). Everything was going just fine, but when I placed the form code and ran the application, the form did not render. My code is exactly like http://framework.zend.com/manual/en/learning.quickstart.create-form.html
On the view, I can dump the form just fine with var_dump($this->form);
I've tried echo $this->form(), echo $this->form->render(), but nothing appeared... What could it be?
This problem can occur when Zend can't find the template file for an element. Look at following code:
$element->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'directory/_input.phtml'
)
)
));
The file _input.phtml must be in the right folder for this Controller. Otherwise Zend can't find the template for input and can't successfully render your element and will not show anything.
Make sure you pass the form to the view from the controller.
In your action handler:
$this->view->form = $my_form;
In your view:
echo $this->form;
I suspected that this was the cause of your problem because Zend Framework doesn't complain if you try to echo a parameter that doesn't exist. (i.e. echo $this->some_fake_parameter won't do anything)
Ok so i tried your code, and it worked for me no problem.
Here is everything:
Controller
<?php
class IndexController extends Zend_Controller_Action
{
public function myTestAction()
{
$form = new Form_Guestbook();
// ... processing logics
if($this->getRequest()->isPost())
{
if($form->isValid($this->getRequest()->getPost()))
{
var_dump($form->getValues());
}
}
$this->view->assign('form', $form);
}
}
Form
<?php
class Form_Guestbook extends Zend_Form
{
public function init()
{
// Set the method for the display form to POST
$this->setMethod('post');
// Add an email element
$this->createElement('text', 'email', array(
'label' => 'Your email address:',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
'EmailAddress',
)
));
// Add the comment element
$this->addElement('textarea', 'comment', array(
'label' => 'Please Comment:',
'required' => true,
'validators' => array(
array('validator' => 'StringLength', 'options' => array(0, 20))
)
));
// Add a captcha
$this->addElement('captcha', 'captcha', array(
'label' => 'Please enter the 5 letters displayed below:',
'required' => true,
'captcha' => array(
'captcha' => 'Figlet',
'wordLen' => 5,
'timeout' => 300
)
));
// Add the submit button
$this->addElement('submit', 'submit', array(
'ignore' => true,
'label' => 'Sign Guestbook',
));
// And finally add some CSRF protection
$this->addElement('hash', 'csrf', array(
'ignore' => true,
));
}
}
?>
View
<?php echo $this->form->render(); ?>
can be seen on: http://yaconiello.com/index/my-test
If this isnt working for you, you may be having a configuration error.
I had a problem like that (exact same form, since it is eclipse example)
My problem was due to misunderstanding. Since I thought that I have to directly access to the view script. I entered in the browser something like: hostname/application/view/script/something.php
But in zend all accesses should be through public folder. You have to access to the view like this: hostname/app_name/public/guestbook
hope that would help you

Categories