Correct way to post a form in cakephp 2.* with client side validation in JavaScript

| By Webner

If we follow cakephp rules to create a form then we can use cakephp inbuilt functionality like we don’t need to assign labels to form fields. Cakephp automatically creates a label for each form field also in case of update/insert validation error messages, the message is automatically shown below the field. In controller, we can directly use posted data in save and update functions there is no need to write extra code to pass into save or update functions.

In View/User/add.ctp file:

<!-- Form name must be same as model name -->
echo $this->Form->create('User', array(
'id' => 'User'
echo __('Add User');
//always set input field name same as column in user table
echo $this->Form->input('name');
echo $this->Form->input('age', array(
'id' => 'age'
echo $this->Form->end(__('Submit'));

$( "#User" ).submit(function( event ) {
var numericReg = /^[0-9]*\.?[0-9]*$/;
var inputVal = $('#age').val();
if(!numericReg.test(inputVal)) {
$('#age').after('<span class="error error-keyup-1" style="color:red">Numeric value only.</span>');
return false;
$( "#User" ).submit();

In Controller/UserController file:

function add() {
if (isset($_POST['data']['User'])) {
$this - > User - > saveAll($this - > request - > data);

Leave a Reply

Your email address will not be published. Required fields are marked *