how to validate form field in cakephp using model and controller - php

I have created a form which I need to validate using model and controller .Here is my form
index.ctp
<?php echo $this->Form->create('Contact',array('url'=>array('controller'=>'contacts','action'=>'add')));
echo $this->Form->text('name');
Model : Contact.php
class Contact extends AppModel
{
var $name = 'Contact';
var $useTable = false;
public $validate = array(
'name' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => false,
'message' => 'Letters and numbers only'
),
'between' => array(
'rule' => array('between', 5, 15),
'message' => 'Between 5 to 15 characters'
)
)
);
}
Controller : ContactsController.php
public function add()
{
$this->Contact->validates();
$this->request->data['Country']['country_name']=$this->request->data['Contact']['country'];
$this->Country->saveall($this->request->data);
$this->redirect('/Contacts/index/');
}
I am trying to do the validation by googling but it seems difficult to me so if anyone could describe the process it would be a great help .My cakephp version is 2.3.8. I just need to validate this name field , as when I click in submit it will show this message in the form.

Your controller code should be like this
The process of validation in CakePHP is like
1) as you have defined validation rules in CakePHP model public `$validates = array();`
2) when ever you do a save on particular model directly or through any association
a callback method beforeValidate for that model gets called to validate the data which is being saved.
3) once the data is validated then beforeSave callback is called after this save method is called.
4) we can also validate the form input fields in controller using $this->Model->validates() but then while saving we have to disable the beforeValidate callback by doing
$this->Model->save($data,array('validate'=>false));
Otherwise you will end validating the same data twice
your controller code should be somewhat like this.
public function add() {
// here we are checking that the request is post method
if ($this->request->is('post')) {
$this->request->data['Country']['country_name']
= $this->request->data['Contact']['country'];
// here we are saving data
if ($this->Contact->saveAll($this->request->data)) {
//here we are setting a flash message for user
$this->Session->setFlash('your record has been added','success');
$this->redirect(array('controller'=>'contacts','action' => 'index'));
} else {
//here we are setting a flash message for user for error if input are not
//validated as expected
$this->Session->setFlash('sorry we could add your record','error');
}
}
}
For more information you can always refer to http://book.cakephp.org/2.0/en/models/callback-methods.html

Related

Combine validated date and non-validated data to store in laravel

Here i have two inputs field as name and age.
I wanna validate name but not age.
How can i send both value to store.
request()->validate([
'name' => 'required',
]);
//Here i wanna add 'age' along with 'name' in $request
//Then i must store.
Pastor::create($request->all());
The $request->all() already sends whatever is in your request. But if you like you can specifically pass request values to create method like this:
Pastor::create([
'name'=> $request->name,
'age' => $request->age
//any other fields
]);
I assume you have named your inputs like i have passed into create method and it should work.
use the Validator class Laravel has. lets say you have UserController
Use Validator;
Use App\User;
class UserController extends Controller
{
// Your Validator
protected function yourValidatorName(array $data)
{
$rules = ['name'=>'required'];
return Validator::make($data,$rules);;
}
// Your Main Function
public function yourFunctionName(Request $request)
{
$isValid = $this->yourValidatorName($request->all());
if(!isValid->fails())
{
// your code here (validation passed)
}
else
{
// your code here (validation failed)
}
}
}
You simply put a check on name field only
$this->validate($request,[
'name' => 'required|min:3|max:200',
],[
'name.required' => 'name is a required field.', // custom messages you can omit them
'name.min' => ' Name must be at least 3 characters.', // custom message for minimum characters
'name.max' => ' Name should not be greater than 200 characters.', // custom message for maximum characters
]);
Pastor::create($request->all());
Without custom messages
$this->validate($request,[
'name' => 'required|min:3|max:200',
]);
Pastor::create($request->all());

Laravel 4 Form Validation should be unique on update form, but not if current

I am trying to validate an update user profile form, whereby the validation should check that the email doesn't exist already, but disregard if the users existing email remains.
However, this continues to return validation error message 'This email has already been taken'.
I'm really unsure where I'm going wrong. Otherwise, the update form works and updates perfectly.
HTML
{{ Form::text('email', Input::old('email', $user->email), array('id' => 'email', 'placeholder' => 'email', 'class' => 'form-control')) }}
Route
Route::post('users/edit/{user}', array('before' => 'admin', 'uses' => 'UserController#update'));
User Model
'email' => 'unique:users,email,{{{ $id }}}'
Your rule is written correctly in order to ignore a specific id, however, you'll need to update the value of {{{ $id }}} in your unique rule before attempting the validation.
I'm not necessarily a big fan of this method, but assuming your rules are a static attribute on the User object, you can create a static method that will hydrate and return the rules with the correct values.
class User extends Eloquent {
public static $rules = array(
'email' => 'unique:users,email,%1$s'
);
public static function getRules($id = 'NULL') {
$rules = self::$rules;
$rules['email'] = sprintf($rules['email'], $id);
return $rules;
}
}
You can accomplish this with the sometimes function of the validator
Something like:
$validator->sometimes('email', 'unique:users,email', function ($input) {
return $input->email == Input::get('email');
});
See http://laravel.com/docs/4.2/validation#conditionally-adding-rules for more info

CakePHP : Validation message not displaying

I'm new to cakePHP and I've made a simple form following some tutorial. On this html form I've used validation. Now the problem is that the validation is working but the message is not displaying what I want it to display. I tried the code below.
Model
public $validate = array(
'title' => array(
'title_required' => array(
'rule' => 'notEmpty',
'message' => 'This is required field'
),
'title_unique' => array(
'rule' => 'isUnique',
'message' => 'This should be unique title'
)
)
);
Controller
public function add() {
if ($this->request->data) {
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash('Post has been added successfully');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Error occured, Please try agan later!');
}
}
}
View
<h2>Add New Post</h2>
<?php
echo $this->Form->create('Post', array('action'=>'add'));
echo $this->Form->input('title');
echo $this->Form->input('body');
echo $this->Form->end('Create Post');
?>
The validation error which I've seen is not the message I mentioned in my controller.
That's built-in browser validation.
Since 2.3 the HTML5 required attribute will also be added to the input based on validation rules.
Your title has the notEmpty rule, so Cake is outputting
<input type="text" required="required" ..
and your browser is triggering that message.
Edit: to override this behaviour, you can do:
$this->Form->input('title', array('required'=>false));
or
$this->Form->submit('Submit', array('formnovalidate' => true));
When you submit the form, your model validation will fire.
From your code what i can see is that you havent included helpers.
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session');
Just add to your controllers and try..
Your Form-create() options are invalid, first argument is the model-name, second is for options:
<h2>Add New Post</h2>
<?php
echo $this->Form->create('Post', array('action'=>'add'));
echo $this->Form->input('title');
echo $this->Form->input('body');
echo $this->Form->end('Create Post');
?>
If the form-helper does not know which 'model' it is creating a form for, I won't check for field validation in the right place, hence, it won't output the validation errors for 'title'
[update] solution above didn't solve the problem. OP has modified the question
Some ideas:
Be sure to enable 'debug' (App/Config/core.php set Configure::write('debug', 2); Otherwise CakePHP may be using a 'cached' version of your model.
If you've named your Model incorrectly, Cake may be automatically generating a model for you, in which case your own model is never actually used, try this for debugging to see if we even 'get' to your model:
Add this to your model;
public function beforeValidate($options = array())
{
debug($this->data); exit();
}

what is the best security practice to escape my data before submitting it into my database in CodeIgniter

i have written a function for insertion into my database. i have a small doubt .
Is my below code provides good security to escape my data before submitting it into my database?
Please suggest me some solution for this if the below code does not provide good way of insetion of data into db
views.php
<? echo form_open('Setups/subject'); ?>
<? echo '<div id="level">'. $subjectname.' : '.form_input($fsubjectname); ?>
<? echo form_submit($submitbtn);
echo form_reset($resetbtn);
echo '</fieldset>'; ?>
<? echo form_close(); ?>
controller.php
class Setups extends CI_Controller {
function subject(){
$this->load->helper('form');
$this->load->model('Setupsmodel');
if($this->input->post('subsubmit')){
$this->Setupsmodel->entry_insert();
}
$data=$this->Setupsmodel->subjectsetup();
$this->load->view('admin/setups/subject_setups',$data);
}
}
model.php
class Setupsmodel extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function subjectsetup()
{
$data['subjectname']='Enter Subject Name';
$data['fsubjectname']=
array('name'=>'subject_name','class'=>'input','size'=>30,'id'=>'txtsubject');
$data['formtopic']='Subject Details Form';
$data['submitbtn'] = array(
'name' => 'subsubmit',
'class' => 'button',
'value' => 'Submit',
'type' => 'submit',
'content' => 'Submit'
);
$data['resetbtn'] = array(
'name' => 'button',
'class' => 'rsetbutton',
'value' => 'Reset',
'type' => 'reset',
'content' => 'Reset'
);
return $data;
}
//--------------Insertion of new record in the table subjectdetails into the db------------
function entry_insert(){
$this->load->database();
$data=array(
'subject_name'=>$this->input->post('subject_name'));
$this->db->insert('subjectdetails',$data);
}
}
You are not filtering your user input, so it's risky. Anyways, CodeIgniter comes with a Cross Site Scripting Hack prevention filter which can either run automatically to filter all POST and COOKIE data that is encountered, or you can run it on a per item basis. By default it does not run globally since it requires a bit of processing overhead, and since you may not need it in all cases. To filter data through the XSS filter you can use following method from security class
$data = $this->security->xss_clean($data);
If you want the filter to run automatically every time it encounters POST or COOKIE data you can enable it by opening your application/config/config.php file and setting this
$config['global_xss_filtering'] = TRUE;
If you use the form validation class, it gives you the option of XSS filtering as well, using set_rules method of form validation class.
$this->form_validation->set_rules('input_name', 'input label', 'xss_clean');
So in this case, you can use in your controller
$this->form_validation->set_rules('subject_name', 'Subject Name', 'xss_clean|required');
if($this->form_validation->run())
{
$this->Setupsmodel->entry_insert();
}
There xss_clean rule will filter the input and required rule will check whether the input is empty or not, so if validation is successful then your insert method will work.

kohana form validation

There is a 'main.php' view that contains a form with email and name fields and a submit button. Eveyrthing works fine with action_index (the code is below), but I'm curious how to modify the code below so it validates if the email was entered correctly. It should not put values in the database if the email field is not valid. I hope it is possible to made using ->rule. Is it? If yes, then how where to add the validation? (I had no luck trying it in different ways).
public function action_index()
{
if ( !empty($_POST) ) {
$model = ORM::factory('tbl1'); // create
$model->values($_POST); // load values to model
if ($model->check()) {
$model->save(); // save the model
} else {
//show errors
}
}
$this->response->body(View::factory('main'));
}
Thank you.
Use rules function in your ORM model:
public function rules()
{
return array(
'email' => array(
array('email', array(':value')),
),
);
}

Categories