Why does ColdFusion think that the value "7+" is a valid integer value, and how I can validate that it is not? - forms

I have a form for users to input quantities. The form has client-side validation to ensure that the value is an integer and within a given range. The action page has server-side validation to ensure that the value is an integer and greater than zero.
However, one type of value gets through the validation and is causing my INSERT/UPDATE queries to throw exceptions. That value is an integer with a plus-sign - ie "7+" or "12+".
When such a value is entered, the ColdFusion-generated JavaScript validation throws a JavaScript error:
_CF_checkformAddToCart = function(_CF_this)
{
//reset on submit
_CF_error_exists = false;
_CF_error_messages = new Array();
_CF_error_fields = new Object();
_CF_FirstErrorField = null;
//form element itemQuantity 'INTEGER' validation checks
if (!_CF_checkinteger(_CF_this['itemQuantity'].value, false))
{
_CF_onError(_CF_this, "itemQuantity", _CF_this['itemQuantity'].value, "Error on itemQuantity, please enter an integer value for quantity that is not greater than 500");
_CF_error_exists = true;
}
//form element itemQuantity 'RANGE' validation checks
if (!_CF_checkrange(_CF_this['itemQuantity'].value, 0.0,500.0, false))
{
_CF_onError(_CF_this, "itemQuantity", _CF_this['itemQuantity'].value, "Error on itemQuantity, please enter an integer value for quantity that is not greater than 500");
_CF_error_exists = true;
}
}
Once I cancel out of the error popup, it goes to the action page, where I [try to] validate the value like so:
<cfif IsValid("integer", form.itemQuantity) AND form.itemQuantity GT 0>
<cfquery>
INSERT ....
However, if try this...
<cfset x = Int("7+") />
...ColdFusion throws an error.
Is it an integer or not ColdFusion???
How can get around this and validate my form input correctly?

isNumeric(form.itemQuantity) will return false for "7+", so to fully validate your input as an int, you can do this
<cfif isNumeric(form.itemQuantity) and IsValid("integer", form.itemQuantity) AND form.itemQuantity GT 0>

Due to the weird and wonderful nature of ColdFusion being typeless. It doesn't know what type of data you are working with and it tries to guess.
Its evaluating that 7+ is a valid. The validation built into ColdFusion makes a lot of assumptions and guesses.
My advise would be to not use it and to write your own validation routines that can be enhanced to do whatever you require.
For example
A user enters
2,075
Is this valid or invalid. Well if you have your own validation you can decide, you can say sure this is an integer and remote the , or you can say no they can't do that.
It's a small investment upfront that will pay off in the long run.

Turns out I can use LSParseNumber() to convert it to valid integer. So, now I'm testing for a valid integer, then resetting it using LSParseNumber() before attempting any database inserts:
<cfset addItemQty = 0 />
<cfif IsValid("integer", Trim(form.itemQuantity))>
<cfset addItemQty = LSParseNumber(Trim(form.itemQuantity)) />
</cfif>
I guess I'll have to re-engineer the front-end client-side validation to properly validate.

Related

Codeigniter form validation callback rule issue

I am using Codeigniter 3.x form validation callback method in combination trim and required to validate a field.
The problem is, when I pipe them: trim|required|callback_some_method, the callback method seems to take precedence over trim and required and shows its error message.
Any ideas on this?
EDIT:
This is the rule:
$this->form_validation->set_rules('new_password', 'New Password', 'trim|required|min_length[8]|callback_password_check');
And this is the password_check method:
function password_check($pwd) {
$containsLetterUC = preg_match('/[A-Z]/', $pwd);
$containsLetterLC = preg_match('/[a-z]/', $pwd);
$containsDigit = preg_match('/\d/', $pwd);
$containsSpecial = preg_match('/[^a-zA-Z\d]/', $pwd);
if ( !($containsLetterUC && $containsLetterLC && $containsDigit && $containsSpecial) ) {
$this->form_validation->set_message('password_check', '{field} must contain UPPERCASE and lowercase letters, digits, and special characters.');
return FALSE;
}
return TRUE;
}
The method should return FALSE, but as long as required is before my custom rule and the field is empty, it should stop there with Required field message, NOT the custom method message.
Okay guys, I've managed to solve it by extending the Form_validation library, putting my callback method there and piping as the other rules (without callback_ prefix).
Unfortunately, as described in the code from CI, callbacks validation rules are always verified first, prior to ‘required’ for instance.
There is an official issue opened at CI : https://github.com/bcit-ci/CodeIgniter/issues/5077

How to Use sendkeys when input type is number with Chrome

HTML
<ion-input [(ngModel)]="login.username" ngControl="username1" type="number" #username1="ngForm" id="userName" required>
</ion-input>
PROTRACTOR TEST CODE
let usern: ElementFinder = element.all(by.css('.text-input')).get(0);
usern.sendKeys('error');
expect(usern.getAttribute("value")).toEqual("error");
browser.sleep(500);
usern.clear();
browser.sleep(1000);
usern.sendKeys('12345');
The element is found but no text is entered into the field. If I change the element to type="text" the protractor command works.And the page view is 'e' and can't be clear.
Secondly if I send string like this: "we2124will", the actually send data is '2124' and the result from getAttribute("value") is 2124.
Thirdly even if I changed the sendKeys to number, the result is not full number string. For example:
Failures:
1) Login page should input username and password
Message:
Expected '125' to equal '12345'.
Stack:
Error: Failed expectation
There are some number missing.
Since you're using an <ion-input>, the actual HTML <input> tag will be nested within, and it won't have an id attribute. The effect is that the wrong element can get selected.
Try something like below to grab the nested input tag:
let username = element(by.id('userName')).all(by.tagName('input')).first();
username.sendKeys('fakeUser');
That worked for me.
As a workaround, you can introduce a reusable function that would perform a slow type by adding delays between send every key.
First of all, add a custom sleep() browser action, put this to onPrepare():
protractor.ActionSequence.prototype.sleep = function (delay) {
var driver = this.driver_;
this.schedule_("sleep", function () { driver.sleep(delay); });
return this;
};
Then, create a reusable function:
function slowSendKeys(elm, text) {
var actions = browser.actions();
for (var i = 0, len = text.length; i < len; i++) {
actions = actions.sendKeys(str[i]).sleep(300);
}
return actions.perform();
}
Usage:
var elm = $("ion-input#userName");
slowSendKeys(elm, "12345");
What version of protractor are you using?
Not sure this is the issue but try grabbing the element by ng-model
var elem = element(by.model('login.username'));
elem.sendKeys('error');
expect(elem.getAttribute("value")).toEqual("error");
elem.clear();
elem.sendKeys('12345');
expect(elem.getAttribute("value")).toEqual("12345");

On a HTML Edit form, what is a good approach to have both reset and remember the posted values features?

I have a form which has both server side and client side validation.
It is an edit form, so the original user values are originally pre-populated.
e.g. The original pre-populated values are:
username = yeo
surname = yang
phonenumber = 11-12345
Now, the user edits to the below and submits.
e.g. The edited submitted values are:
username = yeoNew
surname = yangNew
phonenumber = 12-1111
This gets submitted to the serverside and fails the serverside validation because the phonenumber starting with 12 is not allowed.
Anyway, so the form is displayed back to the user as
e.g. The redisplayed form values are:
username = yeoNew
surname = yangNew
phonenumber = 12-1111
This is because my form allows the user to remember their submitted values.
At this stage, I'd like to allow the user to have the ability to reset the form values to the original values using clientside javascript. This is like a reset feature.
e.g. The reset button will restore the form values to:
username = yeo
surname = yang
phonenumber = 11-12345
The reason for this reset feature is that I want the user to have the option to edit the phonenumber again from the original values.
My question is:
What is a good way to keep track of the original values within the HTML so that I can restore it with javascript?
I'm thinking a new attribute called orig='' within the form elements which will store this value.
Is that a good idea?
Any other approaches?
thanks
I would use the HTML5 local storage.
See http://www.w3schools.com/html/html5_webstorage.asp
Using jquery I would do it this way:
<script type="text/javascript">
function load() {
if (localStorage["username"]) {
$('#username').val(localStorage["username"]);
}
if (localStorage["surname"]) {
$('#surname').val(localStorage["surname"]);
}
if (localStorage["phone"]) {
$('#phone').val(localStorage["phone"]);
}
}
function save() {
localStorage["username"] = $('#username ').val();
localStorage["surname"] = $('#surname').val();
localStorage["phone"] = $('#phone').val();
}
</script>

Contactform 7 Placeholder Validation

I'm using Contactform 7 for Wordpress. I've edited the text.php and textarea.php to enable the use of placeholders. That works fine.
But, the validation isn't working for some input fields, 'cause the validation thinks the placeholder is the actual text being validated. And yes, ofcourse that validates true 'cause it's not empty.
My input fields with placeholders are as follows:
Your name
Your e-mailadress
Your telephone number
and so on.
In contactform 7's scripts.js I want the validation to check if the input isn't the same as the placeholder. So if the input value is the same as the placeholder value, do the CF7's error validation.
Any idea?
In scripts.js of the contactform 7 plugin folder
Change this:
var submit = form.find('input:submit');
if (! submit.length) return;
with this:
var submit = form.find('input:submit');
if (! submit.length || submit == this.find('[placeholder]').wpcf7Placeholder()) return;

Zend_Validate_Date returns true on 2011-02-31

What should i do ?
$edit_end_date = '2011-02-31';
$validator_date = new Zend_Validate_Date(array('format' => 'yyyy-mm-dd'));
$isval = $validator_date->isValid($edit_end_date);
if((!$isval) || empty($edit_end_date))
{
echo "Please Enter Valid End Date. !";
}else{
echo "Entered Is Valid End Date. !";
}
how come it returns true date ?
According to the Zend API Docs, it appears that Zend_Validate_Date will only validate whether the argument passed to it, is a valid date construct (also considers locale), it will not validate if the date actually exists.
Zend_Validate_Date allows you to validate if a given value contains a date. This validator validates also localized input.
-- Edit --
Looks like you can use PHP's built in checkdate() function to determine if a date is valid or not.
There are bugs in data validation (ZF-7583 at issue tracker). Look at Zend_Validate_Date just doesn't work properly
You can use regex validation like in answer to linked question, but it will only check for syntax, not if date exists for real. For this you can use checkdate() - as Mike Purcell suggested - combined with Zend_Validate_Callback:
$validator1 = new Zend_Validate_Regex(
array('pattern' => '/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/')
);
$validator1->setMessage(
"Date does not match the format 'yyyy-mm-dd'",
Zend_Validate_Regex::NOT_MATCH
);
$validator2 = new Zend_Validate_Callback(function($value)) {
// using checkdate() or other function
});