How to set custom message for custom validation in CI - php

I have three field in my html one is mobile_min,mobile_max and third field
i have taken is test which is a input field.So what i have to do i have to
create a custom validation with custom message in which my requirement is mobile_min value should not be greater than mobile_max value after submitting the from.So my code is working fine but i am getting this message "The Min value is not greater than max value field is required." and but i want this message "The Min value is not greater than max value field.".I have also read the custom message rule of CI but it is not working.
Html field code
<html>
<input type=text name=mobile_min>
<input type=text name=mobile_max>
<input type=hidden name=test>
</html>
Controller Validation code
<?php
if($this->input->post('mobile_min')>$this->input->post('mobile_max'))
{
$this->form_validation->set_rules('test', 'Min value is not greater than max value','trim|required');
}
?>
Please help me thanks in Advance.

Use codeigniter form validation call back https://www.codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods
Controller function:
<?php
class Controllername extends CI_Controller {
public function index() {
$this->load->library('form_validation');
$this->load->helper('form');
$this->form_validation->set_rules('mobile_min', 'mobile min', 'required');
$this->form_validation->set_rules('mobile_max', 'mobile max', 'required|callback_somename');
if ($this->form_validation->run() == TRUE) {
/// Success data.
}
$this->load->view('some_view');
}
public function somename() {
if($this->input->post('mobile_min') > $this->input->post('mobile_max')) {
$this->form_validation->set_message('somename', 'Min value is not greater than max value');
return FALSE;
}
}
}
View
<?php echo form_open('controllername'); ?>
<?php echo validation_errors();?>
<?php echo form_input('mobile_min', '', array('id' => 'mobile_min'));?>
<?php echo form_input('mobile_max', '', array('id' => 'mobile_max'));?>
<button type="submit" class="btn btn-primary">Submit</button>
<?php echo form_close();?>

Related

Codeigniter form validation return always false

In my codeigniter controller function call $this->form_validation->run(), that return always false, and my validation_errors() not showing error, probably because not receive datas in post method...
my controller
class Reminder extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('reminder_model');
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->helper('url');
$this->load->library('email');
$this->load->library('session');
if(!$this->session->auth_ok) {
redirect('auth/login');
}
}
public function index(){
$data['title'] = 'Reminder';
$data['section'] = 'reminder';
$data['reminders'] = $this->reminder_model->getReminders();
$data['operatori'] = $this->reminder_model->getOperators();
$this->form_validation->set_rules('selectUser','selectUser', '');
if($this->form_validation->run() === FALSE) {
$this->load->view('common/header2', $data);
$this->load->view('reminder/index', $data);
$this->load->view('common/footerReminder');
echo validation_errors();
}else{
echo "<pre>";
print_r($this->input->post());
die();
}
}
my view
<?php echo form_open('reminder/index'); ?>
<div class="form-group">
<label for="selectUser" style=" width: 30%">Utente: </label>
<select class="form-control" name="selectUser" id="selectUser" style="width: 30%">
<?php foreach($operatori as $operatore): ?>
<option value="<?php echo $operatore['ID']?>" <?php echo $r = ($operatore['ID']==$this->session->auth_user['ID']) ? 'selected' : '' ?>><?php echo $operatore['nome']." ".$operatore['cognome'] ?></option>
<?php endforeach; ?>
</select>
</div>
<button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> View</button>
<?php echo form_close(); ?>
In order to get the entire $_POST array using CodeIgniters built-in methods, you have to set the first parameter as NULL and the second parameter as TRUE
Like this:
$this->input->post(NULL, TRUE);
Also, you have not set any rules for validation..
In CodeIgniter, you set rules in the third parameter of the set_rules method within the form_validation object.
Like this:
$this->form_validation->set_rules($FIELD_NAME, $FIELD_NAME(for error messages), $RULES);
You would substitute the first $FIELD_NAME with the value of the name attribute on the HTML element you are looking to validate.
You would substitute the second $FIELD_NAME with the name you would like to use for the field when displaying an error message to the user.
You would substitute $RULES with the validation rules such as: 'required|min_length[#]|max_length[#]'
Hope this helps!
If you are not setting rules (which makes it rather pointless to use $this->form_validation->set_rules()) the form validation will fail as it's missing a required parameter.
If you don't need to validate a field, don't set a rule.
Try updating your set_rules instruction to $this->form_validation->set_rules('selectUser','selectUser', 'required'); to see if it behaves correctly. You can verify by filling something in the form (validation will pass) or leaving the field blank (validation will fail)
Just remember, if you won't set at least one validation rule for a field, don't instantiate the set_rules method for that field

yii validate an input array of phone numbers

I'm working on a multiple contact form in Yii 1.1.16. Where the user can add multiple phone numbers.
Problem is, how would i validate this using Yii's rules()?
<div class="form-group">
<?php
echo $form->labelEx($model,'contacts', array('class'=>'col-md-3 control-label'));
?>
<div class="col-md-9">
<div class="multiple-contact multiple-form-group input-group padding-bottom-10px" data-max="5">
<div class="input-group-btn input-group-select">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span class="concept">Phone</span> <i class="fa fa-caret-down"></i>
</button>
<ul class="dropdown-menu" role="menu">
<li>Phone</li>
<li>Fax</li>
<li>Mobile</li>
</ul>
<?php echo $form->textField($model,'contacts',array('type'=>'text', 'class'=>'input-group-select-val', 'name'=>'contacts[type][]','value'=>'phone')); ?>
</div>
<?php echo $form->textField($model,'contacts',array('size'=>60,'maxlength'=>255, 'name'=>'contacts[value][]','class'=>'form-control')); ?>
<?php echo $form->error($model,'contacts'); ?>
<span class="input-group-btn">
<button type="button" class="btn btn-success btn-add"><i class="fa fa-plus"></i></button>
</span>
</div>
</div>
</div>
i tried using this, but doesn't work
public function rules()
{
return array(
array('contacts[value][]', 'required'),
array('contacts[value][]', 'integerOnly'=>true),
array('contacts[value][]','type','type'=>'array','allowEmpty'=>false)
);
}
Here is a sample Fiddle on how the jQuery side works. I want it to be able to validate with 'enableAjaxValidation'=>true,. Also, when more fields are added, it duplicates the id of the input. and no ajax post is done onblur/onfocus
Use custom validation.
Declare a custom validator in your rules, and define the validation you require in the validator method.
public function rules()
{
return array(
array('contacts', validateContacts),
);
}
public function validateContacts($attribute,$params)
{
if (length($this->contacts) == 0) {
$this->addError($attribute, 'You must add at least one contact!');
}
foreach($this->contacts as $contact) {
// ...
}
}
In your controller, assign the contacts array to the Model field and call the model's validation method. If there are any errors it will display through the line
<?php echo $form->error($model,'contacts'); ?>
in the view.
The controller contains the code to invoke the validation.
$contactModel = new Contact;
// assign the array of contacts to the model
$contactModel->contacts = $POST['myForm]['contacts']
$contactsModel->validate();
$this->render('myform', contactModel);
If you want the validation to happen through Ajax, you need to specify so when creating your form:
$form=$this->beginWidget('CActiveForm', array(
'id'=>'top-websites-cr-form',
'enableAjaxValidation'=>true,
'clientOptions' => array(
'validateOnSubmit'=>true,
'validateOnChange'=>true),
));
In this case your controller can check for ajax forms.
if(isset($_POST['ajax']) && $_POST['ajax']==='branch-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
references:
http://www.yiiframework.com/wiki/168/create-your-own-validation-rule/
You should make it a separate model with it's own validation.
Then in your controller you have to validate the main models and the related models separately.
Here is a good guide for such a setup:
http://www.yiiframework.com/wiki/384/creating-and-updating-model-and-its-related-models-in-one-form-inc-image/
To my opinion for best validation regarding phonenumbers you should use libphonenumber php library and there is an extension for it regarding yii framework here http://www.yiiframework.com/extension/libphonenumber/
basic usage:
Yii::setPathOfAlias('libphonenumber',Yii::getPathOfAlias('application.vendors.libphonenumber'));
$phonenumber=new libphonenumber\LibPhone($your_phone_number);
$phonenumber->validate();
for more details regarding usage and capabilities of libphonenumber php library you can find here:
https://github.com/davideme/libphonenumber-for-PHP
Let us consider you have a model called ContactNo and it looks like
class ContactNo extends CFormModel
{
public $contact;
public function rules()
{
return array(
// your rules
array('contact', 'required'),
array('contact','length','min'=>2)
);
}
/**
* Declares attribute labels.
*/
public function attributeLabels()
{
return array(
'contact'=>'Contact No',
);
}
}
The controller as SiteController and the action Name as actionIndex
Then your controller should look something like this
public function actionIndex()
{
// set how many contact fields you want here
$contactCount = 3;
$models = array();
if(isset($_POST['ContactNo']))
{
$successModels = 0;
foreach($_POST['ContactNo'] as $key=>$value)
{
$model = new ContactNo;
$model->attributes = $value;
if($model->validate()) // this validates your model
$successModels++; // it tells how many contact No.s have been validated
$models[$key]=$model;
}
// if all the contact nos are validated, then perform your task here
if($successModels === $contactCount)
{
// save your models
echo 'models saved';
Yii::app()->end();
}
}
else
{
for($index = 0;$index < $contactCount; $index++)
$models[] = new ContactNo;
}
$params = array();
$params['contactCount']=$contactCount;
$params['models']= $models;
$this->render('index',$params);
}
Now lets Go to view. Obviously the view is index.php and it will be something like
// Include all the initial part required for activeforms
<?php echo $form->errorSummary($models); ?>
<?php foreach ($models as $index=>$model): ?>
<div class="row">
<?php echo $form->labelEx($model,"[{$index}]contact"); ?>
<?php echo $form->textField($model,"[{$index}]contact",array('size'=>60,'maxlength'=>128)); ?>
<?php echo $form->error($model,"[{$index}]contact"); ?>
</div>
<?php endforeach; ?>
// Include the submit button
Hope this helps you or might give you an idea atleast to achieve your goal.

The field was not set error in codeigniter

I get field was not set error when I'm validating a form
Here is my view
<div class="panel-body">
<h3>Basic Information</h3>
<?php $atrrib = array('class' => 'form-horizontal','role' => 'form');?>
<?php echo form_open('school/shule',$atrrib);?>
<div class="col-md-6">
<div class="form-group">
<label for="add_name" class="col-md-2 control-label">School:</label>
<div class="col-md-7">
<input type="text" class="form-control" name="add_name" id="addSchoolName" placeholder="School name">
</div>
</div>
</div>
<button type="submit" class="btn btn-default">Next</button>
<?php echo form_close();?>
</div>
</div>
</div>
<div class="col-md-2"><?php include_once (APPPATH. 'views/admin/admin_right_column.php');?></div>
</div>
Here is my controller
class School extends CI_Controller {
public function __construct() {
parent::__construct();
}// End of construct
public function shule(){
$this->load->library('form_validation');
if($this->form_validation->run('first_form') === TRUE){
echo 'Valid';
}
else{
if(validation_errors()){
echo validation_errors();
}
$data['title'] = "Add School";
$data['page'] = "admin| add school";
$this->load->view('admin/admin_header',$data);
$this->load->view('admin/add_school',$data);
$this->load->view('admin/admin_footer');
}
}
}
Here is my form_validation configuration
$config['first_form'] = array(
array(
'field' => 'add_name',
'label' => 'School name',
'rules' => 'required|xss_clean|min_length[2]'
)
);
I get an field was not set error when I left the field blank and also I get an Unable to access an error message corresponding to your field name error when I input a single char.
I tried looking where CI fire up your error
Unable to access an error message corresponding to your field name
Then I found this
if ($result === FALSE)
{
if ( ! isset($this->_error_messages[$rule]))
{
if (FALSE === ($line = $this->CI->lang->line($rule)))
{
$line = 'Unable to access an error message corresponding to your field name.';
}
}
else
{
$line = $this->_error_messages[$rule];
}
So this means CI checks if you have not set rule message to the field then check if there is a line that corresponds to the fired function/rule in the form_validation_lang.php file .
So I assumed CI does not find the error message corresponding to your field name because
You have edited/deleted line with the name of the callback/rule
You have created another language file under /application/language with the same name as the default form_validation_lang and haven't defined the rule corresponding to your field name .
Solution is to cross check your lang file if it has a line defined with the same name as your rule or delete any custom language file that has the same name as form_validation_lang.php or you can add up a rule such as
$lang['required'] = 'Name field is required";
or any other rule you have defined in your validation file/function in your custom language file .
try
$this->form_validation->set_rules('add_name', 'School name', 'trim|required||min_length[2]');
if ($this->form_validation->run() == TRUE){
echo 'Valid';
}
else {
$data['title'] = "Add School";
$data['page'] = "admin| add school";
$this->load->view('admin/admin_header',$data);
$this->load->view('admin/add_school',$data);
$this->load->view('admin/admin_footer');
}
and check for errors on view
if(validation_errors()){
echo validation_errors();
}
You can set a custom error message with set_message and use the label from the set_rules function. You can find the documentation here.
Here is an example:
// Set the validation rule
$this->form_validation->set_rules('project_name', 'Project Name', 'trim|required');
// Set the custom message with %s where the label should go
$this->form_validation->set_message('required', '%s is required. Please enter a value.');
// For an invalid project_name, you will get the error:
// Project Name is required. Please enter a value.

Accessing Text Input Field Data

Using CodeIgniter, how do I access and display text entered into an input field on a view file (see code below) from my controller file?
// input_view.php
<?php
echo form_open('search/submit');
$input_data = array('name' => 'search_field', 'size' => '70');
echo form_input($input_data);
form_submit('submit','Submit');
form_close();
?>
When text is entered into an input field, it is impossible to access until the form has been posted back to the server. In other words, the form must be submit for your controller to see it.
Let's say you have a form in the file called input_view.php:
<?php echo form_open('my_controller/my_method'); ?>
<?php echo form_input('search'); ?>
<?php echo form_submit('submit', 'Search'); ?>
When this form is submit, it will be sent to the 'my_controller' controller.
Now, Here's what the my_method should look like if you want to simply print the contents of the search field:
public function my_method() {
if ($this->input->post()) {
$name = $this->input->post('search');
echo $name;
}
}
I hope this helps.

how to get the value of form input box in codeigniter

value of FORM INPUT Help!!
//this is just a refrence of $nm and $fid from test_model//
$data['fid']['value'] = 0;
$data['nm'] = array('name'=>'fname',
'id'=>'id');
say i have one form_view with
<?=form_label('Insert Your Name :')?>
<?=form_input($nm)?>
and a function to get single row
function get($id){
$query = $this->db->getwhere('test',array('id'=>$id));
return $query->row_array();
}
then in controller.. index($id = 0)
and somewhere in index
if((int)$id > 0)
{
$q = $this->test_model->get($id);
$data['fid']['value'] = $q['id'];
$data['nm']['value'] = $q['name'];
}
and mysql table has something like 1. victor, 2. visible etc. as a name value
but here its not taking the value of name and id from form_input and not showing it again in form_view in same input box as victor etc so to update and post it back to database...
anyone please help!!
and please be easy as I am new to CI!!
Based on your comment to my first answer, here is a sample of a Controller, Model and View to update a user entry pulled from a table in a database.
Controller
class Users extends Controller
{
function Users()
{
parent::Controller();
}
function browse()
{
}
function edit($id)
{
// Fetch user by id
$user = $this->user_model->get_user($id);
// Form validation
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'required');
if ($this->form_validation->run())
{
// Update user
$user['name'] = $this->input->post('name', true);
$this->user_model->update_user($user);
// Redirect to some other page
redirect('users/browse');
}
else
{
// Load edit view
$this->load->view('users/edit', array('user' => $user));
}
}
}
Model
class User_model extends Model
{
function User_model()
{
parent::Model();
}
function get_user($user_id)
{
$sql = 'select * from users where user_id=?';
$query = $this->db->query($sql, array($user_id));
return $query->row();
}
function update_user($user)
{
$this->db->where(array('user_id' => $user['user_id']));
$this->db->update('users', $user);
}
}
View
<?php echo form_open('users/edit/' . $user['user_id']); ?>
<div>
<label for="name">Name:</label>
<input type="text" name="name" value="<?php echo set_value('name', $user['name']); ?>" />
</div>
<div>
<input type="submit" value="Update" />
</div>
<?php echo form_close(); ?>
It's hard to see the problem from your snippets of code, please try and give a little more information as to the structure of your app and where these code samples are placed.
Presume in the last code listing ('somewhere in index') you are getting $id from the form, but you define the ID of the form input box as 'id' array('name'=>'fname','id'=>'id') rather than an integer value so maybe this is where the problem lies.
Where does the $data array get passed to in the third code listing?
From your question I think you want to display a form to edit a person record in the database.
Controller code
// Normally data object is retrieved from the database
// This is just to simplify the code
$person = array('id' => 1, 'name' => 'stephenc');
// Pass to the view
$this->load->view('my_view_name', array('person' => $person));
View code
<?php echo form_label('Your name: ', 'name'); ?>
<?php echo form_input(array('name' => 'name', 'value' => $person['name'])); ?>
Don't forget to echo what is returned from form_label and form_input. This could be where you are going wrong.

Categories