In CakePHP validation, do I need a notEmpty rule if I have another rule like alphaNumeric and allowEmpty is false? - validation

If I have a validation rule such as
alphaNumeric' => array(
'rule' => array('alphaNumeric'),
'allowEmpty' => false),
Is there any need to have a notEmpty rule? As I understand it, the allowEmpty being set to false will consider empty values a violation of the alphaNumeric rule, so other than if I wanted to define two different error messages, is there any need for a notEmpty rule?
(Another way to ask this question: is there some separate functionality that a standalone notEmpty rule would provide or be necessary for, other than to give a separate custom message, that I'm not seeing?)
To be perfectly clear: I understand that idea that notEmpty is a standalone rule, where allowEmpty is an attribute of a rule. That's not my question. My question is, is there any need or value to adding a notEmpty rule (other than the custom message that it would allow you to have for that rule), if you already have an alphaNumeric (or some other similar) rule you can just add allowEmpty = false to? Is there any difference in what the rule vs the attribute does, other than the rule being stand alone?

It really depends on the "other" rule that you're using.
You can see exactly what each rule is ACTUALLY checking for in the CakePHP Validation utility:
https://github.com/cakephp/cakephp/blob/44b7d013ae304a05699179bb4ea0077956c57e10/lib/Cake/Utility/Validation.php
For instance, in that file you can see the alphanumiric check:
public static function alphaNumeric($check) {
if (is_array($check)) {
extract(self::_defaults($check));
}
if (empty($check) && $check != '0') {
return false;
}
return self::_check($check, '/^[\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]+$/Du');
}
In the case of alphanumeric, you can see that it has an empty check already, so you shouldn't also need the allowEmpty=>false rule.
Lastly, to your point, the only benefit I see in adding it as a separate rule is that you can give a better error message to the user.

Please read... http://book.cakephp.org/2.0/en/models/model-attributes.html
Model attributes allow you to set properties that can override the default model behavior and rules in your context is the business logic of your application.
The answer of your question lies in the below link:
http://book.cakephp.org/2.0/en/models/data-validation.html#allowempty
Actually you are absolutely correct, if you there is field in which you have to apply more than one validation, eventually one is nonEmpty in that case you can simply use allowEmpty=>false.
But if your datafield requires only one validation for non empty check in that case you should use nonEmpty for better understanding of your code!
I guess I had made my point...thanks

Related

Using validationRules in Models to validate form Codeigniter 4

So I have these variables $skipValidation (set specifically to FALSE), $validationRules, $validationMessages set according to this documentation
but for the life of me I can't figure out what trigger this $validationRules to run, I just assume that $skipValidation meant Codeigniter-4 already got me covered (automatically validates input before doing any queries)..
I even put $UserModel->errors() in case the validation rules catch an error
if($userModel->insert($data) === false) {
return view('form', ['validation' => $userModel->errors()])
} else {
redirect()->to('home');
}
I have these rules required and min_length[] applied to $validationRules but the model just skips the validationRules and insert it immediately to database rendering $validationRules useless..
Any ideas how to get validationRules in Models working? or how is it supposed to be used? I keep looping in the documentation because I don't know any better.
Dumb me, i was trying to figure out what is wrong with the code this whole time when its just a simple problem.. i have two models with the same filename (backup project) and i blindly edits model file that is inside the backup project..
Perhaps for future readers seeking an answer, don't forget to check your folder path for your model file, you might make the same mistake as i did.

Vuetify default rules implementation

I am using Vuetify and use its default way of adding rules to input fields.
I know there is this rule:
v => !!v
This checks if the the form input isn't empty. But how can I make it in such a way that it only accepts alphabetical letters, numbers or even apply a regex to it? I can't find anything in the docs. Can someone with any experience help me out?
So I assume that you've probably sorted this now but for anyone finding this from google etc.
To add a new rule, you need to add it to your vue component, either through an import or just adding it straight to your data object. You name it as you would any other data property and it's an array of the tests like the v => !!v one you mentioned. You then add the OR operator followed by the text to show on a failed validation.
So to add a regex that only allows letters you would have this:
data () {
return {
alphaRule: [
v => /[a-zA-Z]+$/.test(v) || 'Field must only contain letters'
]
}
}
then on your form field you would have <v-text-field :rules="alphaRule"></v-text-field>
That said, I would highly recommend adding all of your rules to a Rules.js file and binding the rules globally so that you can access them anywhere, have a centralised repository for them, and it helps keeps your code DRY too.
I have just made a big ol list of rules inspired by Laravel's Validation rules and will edit my answer to include them oncce I have finished testing them.
EDIT
Here are all the rules I'm currently using in production. Hopefully they'll help someone else! You'll need to import them into your component to use them, or you can globally include them through a vue mixin.

Laravel validation required rule not working

I need to add required rule if one field is available. Also need to check if it is an integer and 10 digit. So I added the rule like below.
'id_number' => 'sometimes|required|digits:10|integer'
Validations works only when the field is available. But here required rule is not working. It directly shows integer error even if the field is empty.
I use Laravel 5.1
Finally I figured it!
You need to change the order of required rule to last. It works when I add rule like this,
'id_number' => 'sometimes|digits:10|integer|required'

Codeigniter form validation, custom check doesn't work if the field is not required

Gah.. I have spent way to long on this, but I believe I have found the problem.
Essentially I have a hidden field which is populated when a user clicks on an image.
It is required that the user has clicked the image but I do not want the generic form error message for a 'required' check with the CI form validation class.
As such I quickly made a image_required function in my extended form validation class, and set a rule such that this rule was applied to the hidden field.
function image_required($str)
{
$CI =& get_instance();
$CI->form_validation->set_message('image_required','Please click the image above.');
if($str != '')
{
return TRUE;
}
else
{
return FALSE;
}
}
If the hidden field was blank no error was being called.
I am led to believe now that this is because CI says this field is empty yet it is not 'required', therefore we will ignore all the other validation rules for the field. Is this correct?
If so how can i go about requiring this field be set but having a custom error message?
bangs head
Thanks
If you look at the source code (v2.1.3) for the '_execute' routine (system/libraries/Form_validation.php) you will see on line 486
// If the field is blank, but NOT required, no further tests are necessary
So you are correct, it needs to be required and then it will process your rule.
In order to fix it so you can have a non-required blank field that still processes rules, you should override the '_execute' method by creating a file called 'MY_Form_validation.php' in the application/libraries folder (I think, you might need to check exactly how you extend an existing library) and then copy the '_execute' method and alter the code to continue on a non-required but blank entry.
I do love CI, but I have to say this does not allow the flexibility required. It is perfectly reasonable to have a field that cannot be empty, but is NOT required. As in, you wouldn't enforce "user MUST enter a value", but they cannot submit a blank. I think someone got confused between EMPTY and REQUIRED.
1) REQUIRED: User MUST put a value in the field and it cannot be empty (i.e. '')
2) EMPTY: User does not HAVE to enter a value, BUT, if they do, it's cannot be empty. This not the same as REQUIRED... Looks like I'll be using a callback again.
REQUIRED incorporates two logical steps (1->Must enter a value, and 2->Cannot be empty) these two steps should be separated logically to allow either / or.
In constraint terms it would be either, REQUIRED, NOT NULL. Or NOT REQUIRED, NOT NULL.

blacklisting vs whitelisting in form's input filtering and validation

which is the preferred approach in sanitizing inputs coming from the user?
thank you!
I think whitelisting is the desired approach, however I never met a real whitelist HTML form validation. For example here is a symfony 1.x form with validation from the documentation:
class ContactForm extends sfForm
{
protected static $subjects = array('Subject A', 'Subject B', 'Subject C');
public function configure()
{
$this->setWidgets(array(
'name' => new sfWidgetFormInput(),
'email' => new sfWidgetFormInput(),
'subject' => new sfWidgetFormSelect(array('choices' => self::$subjects)),
'message' => new sfWidgetFormTextarea(),
));
$this->widgetSchema->setNameFormat('contact[%s]');
$this->setValidators(array(
'name' => new sfValidatorString(array('required' => false)),
'email' => new sfValidatorEmail(),
'subject' => new sfValidatorChoice(array('choices' => array_keys(self::$subjects))),
'message' => new sfValidatorString(array('min_length' => 4)),
));
}
}
What you cannot see, that it accepts new inputs without validation settings and it does not check the presence of inputs which are not registered in the form. So this is a blacklist input validation. By whitelist you would define an input validator first, and only after that bind an input field to that validator. By a blacklist approach like this, it is easy to forget to add a validator to an input, and it works perfectly without that, so you would not notice the vulnerability, only when it is too late...
A hypothetical whitelist approach would look like something like this:
class ContactController {
/**
* #input("name", type = "string", singleLine = true, required = false)
* #input("email", type = "email")
* #input("subject", type = "string", alternatives = ['Subject A', 'Subject B', 'Subject C'])
* #input("message", type = "string", range = [4,])
*/
public function post(Inputs $inputs){
//automatically validates inputs
//throws error when an input is not on the list
//throws error when an input has invalid value
}
}
/**
* #controller(ContactController)
* #method(post)
*/
class ContactForm extends sfFormX {
public function configure(InputsMeta $inputs)
{
//automatically binds the form to the input list of the #controller.#method
//throws error when the #controller.#method.#input is not defined for a widget
$this->addWidgets(
new sfWidgetFormInput($inputs->name),
new sfWidgetFormInput($inputs->email),
new sfWidgetFormSelect($inputs->subject),
new sfWidgetFormTextarea($inputs->message)
);
$this->widgetSchema->setNameFormat('contact[%s]');
}
}
The best approach is to either use stored procedures or parameterized queries. White listing is an additional technique that is ok to prevent any injections before they reach the server, but should not be used as your primary defense. Black listing is usually a bad idea because it's usually impossible to filter out all malicious inputs.
BTW, this answer is considering you mean sanitizing as in preventing sql injection.
WL is a best practice against BL whenever it is practicable.
The reason is simple: you can't be reasonably safe enumerating what it is not permitted, an attacker could always find a way you did not think about. If you can, say what is allowed for sure, it is simpler and much much safer !
Let me explain your question with few more question and answer.
Blacklist VS Whitelist restriction
i. A Blacklist XSS and SQL Injection handling verifies a desired input against a list of negative input's. Basically one would compile a list of all the negative or bad conditions, and verifies that the input received is not one among the bad or negative conditions.
ii. A Whitelist XSS and SQL Injection handling verifies a desired input against a list of possible correct input's. To do this one would compile a list of all the good/positive input values/conditions, and verifies that the input received is one among the correct conditions.
Which one is better to have?
i. An attacker will use any possible means to gain access to your application. This includes trying all sort of negative or bad conditions, various encoding methods, and appending malicious input data to valid data. Do you think you can think of every possible bad permutation that could occur?
ii. A Whitelist is the best way to validate input. You will know exacty what is desired and that there is not any bad types accepted. Typically the best way to create a whitelist is with the use of regular expression's. Using regular expressions is a great way to abstract the whitelisting, instead of manually listing every possible correct value.
Build a good regular expression. Just because you are using a regular expression does not mean bad input will not be accepted. Make sure you test your regular expression and that invalid input cannot be accepted by your regular expression.
Personally, I gauge the number of allowed or disallowed characters and go from there. If there are more allowed chars than disallowed, then blacklist. Else whitelist. I don't believe that there is any 'standard' that says you should do it one way or the other.
BTW, this answer is assuming you want to limit inputs into form fields such as phone numbers or names :) #posterBelow
As a general rule it's best to use whitelist validation since it's easier to accept only characters you know should go there, for example if you have a field where the user inputs his/her phone number you could just do a regex and check that the values received are only numbers, drop everything else and just store the numbers. Note that you should proceed to validate the resulting numbers as well. Blacklist validation is weaker because a skilled attacker could evade your validation functions or send values that your function did not expect, from OWASP "Sanitize with Blacklist":
Eliminate or translate characters (such as to HTML entities or to remove quotes) in an effort to make the input "safe". Like blacklists, this approach requires maintenance and is usually incomplete. As most fields have a particular grammar, it is simpler, faster, and more secure to simply validate a single correct positive test than to try to include complex and slow sanitization routines for all current and future attacks.
Realize that this validation is just a first front defense against attacks. For XSS you should always "Escape" your output so you can print any character's needed but they are escaped meaning that they are changed to their HTML entity and thus the browser knows it's data and not something that the parser should interpret thus effectively shutting down all XSS attacks. For SQL injections escape all data before storing it, try to never use dynamic queries as they are the easiest type of query to exploit. Try to use parameterized store procedures. Also remember to use connections relevant to what the connection has to do. If the connection only needs to read data, create a db account with only "Read" privileges this depends mostly on the roles of the users. For more information please check the links from where this information was extracted from:
Data Validation OWASP
Guide to SQL Injection OWASP
The answer generally is, it depends.
For inputs with clearly defined parameters (say the equivalent of a dropdown menu), I would whitelist the options and ignore anything that wasn't one of those.
For free-text inputs, it's significantly more difficult. I subscribe to the school of thought that you should just filter it as best you can so it's as safe as possible (escape HTML, etc). Some other suggestions would be to specifically disallow any invalid input - however, while this might protect against attacks, it might also affect usability for genuine users.
I think it's just a case of finding the blend that works for you. I can't think of any one solution that would work for all possibilities. Mostly it depends on your userbase.

Resources