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.
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 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
I wrote a custom validation method inside my Submission model that basically allows a blank input field, but once someone enters something in it, it'll validate the data entered.
The validation inside my Submission Model looks like this (All other validation rules are working except for 'description'):
var $validate = array(
'title' => array(
'title' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a title'
),
'minLength' => array(
'rule' => array('minLength', 5),
'message' => 'Please make your title longer'
),
'maxLength' => array(
'rule' => array('maxLength', 300),
'message' => 'Your title needs to be shorter'
),
),
'description' => array(
'checkDescription' => array(
'rule' => array('validateDescription'),
'message' => 'Description must be greater than 5 characters'
),
),
'source' => array(
'source' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Enter a valid source URL'
),
'website' => array(
'rule' => 'url',
'message' => 'Please enter a valid source URL'
),
)
);
My method which is also in my Submission model (below the above code) is:
public function validateDescription($data) {
if(empty($data['Submission']['description']))
return true;
if((strlen($data['Submission']['description'])) <= 5)
return false;
}
I'm not sure why this isn't working at all. In my view, I've got this to display the error:
if ($form->isFieldError('Submission.description'))
echo ($form->error('Submission.description', null, array('class' => 'error')));
The only reason I'm trying to do this, is because using the normal validation with required => false and allowEmpty => true along with a minLength and maxLength validation rule weren't behaving how I intended.
Any help would be greatly appreciated! :)
The $data variable passed into the validation method only contains array($fieldname => $value). You're also not returning true for strings over length of 5. Your method should look like this:
public function validateDescription(array $data) {
$value = current($data);
return !$value || strlen($value) > 5;
}