I am trying to enforce the first name of my model to be any character but numbers, but so far it's not working as expected. When I try this:
public $validate = array(
'first_name' => array(
array(
'rule' => array('custom', '/^[\d]+/'),
'message' => 'Please fill in a valid first name'
)
)
);
it doesn't work because I'm able to save 4 as the name. If I move the negation to within the brackets like so:
public $validate = array(
'first_name' => array(
array(
'rule' => array('custom', '/[^\d]+/'), //allow anything but numbers
'message' => 'Please fill in a valid first name'
)
)
);
It also doesn't work because I'm able to save a4 as the name. So how can I get best of both worlds without having to include both custom validation rules?
/^[^\d]+$/ allows anything but numbers
Related
Is there any cakephp validation for numbers only. That input field should only accept Numbers whether its float OR integer.
I have this field validation in model, But I don't know what rule to use.
'payment_commission' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Required.'
)
)
Any help is much appreciated..
You want to use numeric to test for valid numbers:-
'payment_commission' => array(
'required' => array(
'rule' => 'notEmpty', // use notBlank as of CakePHP 2.7
'message' => 'Required.'
),
'numeric' => array(
'rule' => 'numeric',
'message' => 'Numbers only'
)
)
You can alternatively use decimal to check for floats or naturalNumber for natural numbers. Full details can be found in the offical docs.
You can also make sure that the input field only allows for numeric values:-
<?= $this->Form->input('payment_commission', ['type' => 'number']) ?>
This has the added advantage that on some mobile devices the keyboard will switch to a number pad for easier input. It's important to ensure that the server-side validation (the Cake part) is in place though as there are ways for people to get round client-side validation.
You can try below cakePHP code for number validation.
'payment_commission' => array(
'numeric' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Required.'
)
)
)
You can use below html pattern code in for your textbox.
<input type="text" name="payment_commission" pattern="[0-9]{10}" title="Three letter country code">
Here you can manage your pattern by changing [0-9]{10}. ([0-9] = expected integers from User, {10} = length).
You can use following rule to validate numbers(float and integer):
'payment_commission' => array(
'numeric' => array(
'rule' => array('decimal', 2),
'message' => 'Please enter only numbers',
'allowEmpty' => false,
'required' => true,
)
),
Let me know if this works for you.
i installed a plugin on my firefox browser which is called "SQL Inject Me" and then I tried it against my Cakephp website. I see that it was able to inject few blank accounts (some with password) and some without password. The database is not allowed to accept null values for username, emails etc also I'm not sure how is it able to bypass cakephp validation.
my cakephp validation for username field
'username' => array(
'username must not be empty' => array(
'rule' => 'notEmpty',
'message' => 'username field cannot be empty'
),
'username must be unique' => array(
'rule' => 'isUnique',
'message' => 'username is already taken'
)
'username must not contain special character' => array(
'rule' => 'usernameValidation',
'message' => 'username can only contain numbers, characters, underscores, dashes and Periods. Underscore, dash and Period are only allowed in the middle.'
)
)
I think your validations has wrong keys. That should be like this..
var $validate = array(
'username' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'username field cannot be empty'
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'username is already taken'
)
'usernameValidation' => array(
'rule' => 'usernameValidation',
'message' => 'username can only contain numbers, characters, underscores, dashes and Periods. Underscore, dash and Period are only allowed in the middle.'
)
)
)
and while saving them you just have to call validate function to go through the validation rules. Below link can help you to how to validate from controller while saving the data.
http://book.cakephp.org/2.0/en/models/data-validation/validating-data-from-the-controller.html
Thanks..!
Add the keys 'required' => true, 'allowEmpty' => false to your validation arrays.
Validations were failing because if you remove fields from a form using developers tools like firebug then cakephp validations will not work for those removed fields.
what i did to fix these issues is to use this code right before passing data to save method.
if(!(isset($this->request->data['User']['email']))){
$this->request->data['User']['email']='';
}
if(!(isset($this->request->data['User']['username']))){
$this->request->data['User']['username']='';
}
if(!(isset($this->request->data['User']['password']))){
$this->request->data['User']['password']='';
}
if(!(isset($this->request->data['User']['confirm_password']))){
$this->request->data['User']['confirm_password']='';
}
If there is a missing field then this code will add that field and assign an empty string to it. Then those fields will be eligible for validation and will eventually fail validation.
I'm using CakePHP 2.3.8 and I'm trying to figure out if there's a way to set certain validation rules to required on the fly.
For example, my User model has phone_number, username, email, and password validation. If a user wants to change their username, their phone number isn't required to do so. That means I can't set it to required, because then when changing a username, the phone_number will be expected to be present in the data.
public $validate = array(
'username' => array(
'minLength' => array(
'rule' => array('minLength', '3'),
'message' => 'A username with a minimum length of 3 characters is required'
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'This username has already been taken.'
)
),
'email' => array(
'email' => array(
'rule' => array('email'),
'message' => 'Please enter a valid email address.',
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'This email address is already in use'
)
),
'password' => array(
'rule' => array('minLength', '8'),
'message' => 'A password with a minimum length of 8 characters is required'
),
'phone_number' => array(
'rule' => array('valid_phone'),
'message' => 'Invalid phone number',
)
);
To get around this problem, in my controller for the corresponding action what I've been doing is checking to make sure the expected inputs have been posted. If not, set that index to null so that it is validated...such as
public function change_username(){
if(!isset($this->request->data['username'])){
$this->request->data['username'] = null;
}
$this->ExampleModel->set($this->request->data);
//if it wasn't posted, the username index will be created but set to null. This is my workaround for setting something to "required"
if($this->ExampleModel->validates() == true){
//do something
}
else{
//do something
}
}
While this works, I feel like it makes for a lot of extra coding, especially if I have a form that has a lot of inputs.
I've also tried to validate only the inputs that I need, but unless the data was posted, it ignores them. For example
if($this->ExampleModel->validates(array('fieldList' => array('phone')) == true){
.....
}
If "phone" wasn't posted, it doesn't validate it.
Is there any way to set required for a given input's validation to true on the fly? I found this article on using multiple validation rulesets and while it would accomplish what I want, there would be a lot of re-coding involved.
Before validation, can I set an input to required?
Firstly, in your Model validation rules you have phone_number but yet trying to validate phone, there aren't validation rules for phone.
It would be ideal request->data[] to match model fields, you can rebuild an array etc.
From book.cakephp:
This will add a single rule to the password field in the model. You can chain multiple calls to add to create as many rules as you like:
$this->validator()
->add('password', 'required', array(
'rule' => 'notEmpty',
'required' => 'create'
))
->add('password', 'size', array(
'rule' => array('between', 8, 20),
'message' => 'Password should be at least 8 chars long'
));
I want to to set validation rule in model for user enter only special character only into text field .so please suggest me proper solution.
demo code is
public function addValidations()
{
parent::addValidations();
$this->validate['Field name'] = array
(
'notempty' => array
(
'rule' => array('special char', 'msg',),
'allowEmpty' => false,
'message' => 'Enter Special character only.',
),
);
}
you can define Custom Regular Expression Validation
public $validate = array(
'login' => array(
'rule' => '/^[\W]+$/',
'allowEmpty' => false,
'message' => 'Enter Special character only.'
)
)
// '/^[\w.-]+$/' this will allow only special character.
I want to use model validation.
lets i explain here clearly. in my view there is a file called "register.ctp". Also i have two table one is users and another is profiles, according to cakephp concept also i have two model that user model(User.php) and profile model(Profile.php).
My register.ctp contains the follow fields
name, email, address and phone all are mandatory - when i submit, name and email will store in users table and address and phone will store in profiles table
when i use model validation i have tried by using the below code that is working only for name and email but not working on for other fields.
here is my code for for model validation in user model(User.php)
public $validate = array(
'email' => array(
'blank' => array(
'rule' => 'notEmpty',
'message' => 'Please enter Email.'
)
),
'name' => array(
'rule' => 'notEmpty',
'message' => 'Please enter Name'
),
'address' => array(
'rule' => 'notEmpty',
'message' => 'Please enter Address'
),
'phone' => array(
'rule' => 'notEmpty',
'message' => 'Please enter Phone'
),
);
Thanks
You need to set the validation per model.
So in User.php:
public $validate = array(
'email' => array(
'blank' => array(
'rule' => 'notEmpty',
'message' => 'Please enter Email.'
)
),
'name' => array(
'rule' => 'notEmpty',
'message' => 'Please enter Name'
)
);
And in Profile.php:
public $validate = array(
'address' => array(
'rule' => 'notEmpty',
'message' => 'Please enter Address'
),
'phone' => array(
'rule' => 'notEmpty',
'message' => 'Please enter Phone'
)
);
And you need to validate both models in the Controller:
$this->User->set($this->data());
$valid = $this->User->validates();
$this->Profile->set($this->data);
$valid = $valid && $this->Profile->validates();
See these two model methods.
Model::validateAssociated() Validates a single record, as well as all its directly associated records.
Model::validateMany() validates multiple individual records for a single model
See Model::saveAll() as well. It can be used to validate the whole set of records and associated records. This will only validate but not save the reocrds as well:
$this->saveAll($data, array('validate' => 'only'));
I recommend you to read the whole documentation about saveAll() to understand how it works and what it will return when you only validate the data.
There is no need to manually validate each model one by one like noslone suggested. The single line above will do it as well.