IE11 and input type="number" - php

I have a form with input type="number" which is giving me problems in IE11: some values are accepted and some others are not, apparently randomly.
Here's the code:
<input type="number" style="text-align:right" min="1.00" placeholder="1,00" name="value-name" id="value" step="0.01" title="title" required/>
For some reason IE11 accepts 9.2, 9.4, 9.5, 9.6, 9.7, 9.9 but refuses 9.3 and 9.8. This is just an example, it's happening with all numbers and I'm not understanding the reason behind it. Moreover some numbers were accepted some minutes ago but now they aren't anymore.
In addition to this, all of the previous values should not be valid because I'm in Europe and , is the delimiter for the decimal part, not .. Instead, when I use ,, IE does not traslates it to . and, when passed to PHP through a POST, PHP's is_numeric() returns false!
How can I make all of this work? Thanks

I fixed this by accepting both . and , as decimal dividers.
I added the attributes formnovalidate lang="en" to the form input and performed the form validation through Javascript, with the following code:
function validateForm(minValue) {
var number = document.getElementById("value").value.replace(",",".");
if(number != "") {
var isNaNres = isNaN(parseFloat(number));
var isFiniteRes = isFinite(number);
if (!isNaNres && isFiniteRes && number >= minValue && number.match("^[0-9]+(\.[0-9]{1,2})?$"))
return true;
}
alert("<Error message>");
return false;
}
The regular expression match was needed to guarantee that the number had at maximum 2 decimal places

Related

How to count integer values stored in a variable using php?

I am developing a web form which have a field 'marks' where user can put marks... I want to force the user to input only marks less then 4 digits. Here is function for this purpose but it is not working...
Function validate($marks)
If(strlen($marks)<=4 && !filter_var($marks, FILTER_VALIDATE_INT)
)
Return false;
Else
Return true ;
This can be achieved using only HTML5 input options (PHP is unnecessary for this application).
If your input is type="number" you can use min=-9999 max=9999 to limit the number to 4 digits.
If your input is type="text" you can use maxlength=4 to limit to 4 characters.
Here is a list of input types and options that might help: https://www.w3schools.com/tags/tag_input.asp
Use the maxlength attribute of the input tag.
e.g.
<input type='text' maxlength='4' name='marks' />
Depending on how you want to implement this, you can use javascript too, which will allow you to display some dynamic warning info when it is less than 4 digits.
If you want to do it with php you can do it like this if the data type is an integer or a float:
if ($marks <= 9999.99) {
//do something
}
If it is a string representation of numbers, you can do it like this:
if (strlen($marks) <= 4) {
// do something
}

Number validation in html form using php

I have created a form where the amount filed is like
<label for="amt"<?php validateField( "amt", $Fieldsmissing ) ?>>Amt *</label>
<input type="number" name="amt" id="amt" min="1" value="<?php setValue( "amt" ) ?>" />
and in the top of the form the condition is like
function setValue( $fieldName ) { if ( isset( $_POST[$fieldName] ) && $_POST[$fieldName] > 0 ) { echo $_POST[$fieldName]; } }
After submitting, it shows error if I have input 0 however if I put 00 or any '-' sign or any alphabets instead of 0, it does not validates.
As I know that the number type has a bug in Mozila, IE but it works fine in Chrome because Chrome does not accept any input below 1. What I am looking for is, I want to set input value ranging from 0.1 to maximum positive number (i.e 99999). Apart from that, if it inputs anything else it will show error. Can any one please tell me what condition will be best suited for my form.
Thanks.
The full source code is given here for your understanding, it would be appreciated if you have a look on here
Check out these functions:
intval: Returns the integer value of var, using the specified base for the conversion (the default is base 10). intval() should not be used on objects, as doing so will emit an E_NOTICE level error and return 1.
filter_var: Filters a variable with a specified filter. (FILTER_VALIDATE_INT in your case.
settype Set the type of a variable. (integer)
So, try this:
function setValue($fieldName)
{
if (isset($_POST[$fieldName]))
{
$field = intval($_POST[$fieldname]);
}
// other magic
}

php validation concept

First of all, I don't want to use any framework but I am looking for a good way to use whitelist validation. I am going to apply it on all the user input I receive, I need validation for XSS protection and I also want to apply different formats for example:
Example 1 XSS.
<input type="text" name="test" value="<script>alert('test');</script" />
Example 2 Date.
<input type="text" name="test" value="31-05-2012" />
Example 3 Time.
<input type="text" name="test" value="15:00" />
Example 4 Max length.
<input type="text" name="test" value="short description" />
Example 5 Min length.
<input type="text" name="test" value="min description" />
Example 6 Alphabetic and default symbols only
<input type="text" name="test" value="hello world. This is à ö text input :P :) :S :$ =D !! ??" />
Example 7 Numeric only
<input type="text" name="test" value="1234567890" />
My idea is to build a clientside and server site validation, if the user gets passed through the clientside validation (jQuery) they will get marked as hacker, since it is impossible for default users to pass through the clientside validation.
My question is: What would be the best way to apply client+serverside validation to prevent XSS and apply regular expressions on fields. Are there any lightweight PHP libraries for validation?
I have looked at:
ctype_alpha
preg_match
But I am not quit sure what would be the best one to use, and ctype_alpha is not allowing default symbols etc.
Any advises? Examples? Thanks for your time and reading, and sorry for the hectic question.
It seems you just need some basic validation, not "whitelist" one.
the idea is quite simple.
Create a server-side validation. with ctype_alpha, preg_match and such. (I hope that your question is not about teaching you these functions from scratch).
Create cleint-side validation if you want, by making AJAX calls to the very same validation routines you've used for the (1).
Of course, you have to use both anyway.
Marking users as a hackers seems not the best idea. What you gonna do with marked users?
I've had a similar problem and ended up writing my own "Input-Datatype" classes. This might be a bit excessive if you only use them for validating input though. But you could build validation functions that use a mix of PHP functions such as preg_match, is_numeric, strtotime etc...
An example for date validation would be:
public function validate(&$value) {
$date = strtotime($value);
if($date === false){
//Error no valid date
}else{
if(isset($this->maxDate)){
if($date>strtotime($this->maxDate)){ //maxDate being the maximal date allowed
//Error max date exceeded
}
}
if(isset($this->minDate)){
if($date<strtotime($this->minDate)){ //minDate being the minimal date allowed
//Error date too low
}
}
$value = strftime($this->format,$date); //format being the format in which the date should be saved
}
Another example for validating text could be:
public function validate(&$value) {
if (isset($value) && $value != "") {
if(isset($this->maxLength)&&$this->maxLength!= ""){ //maxLength being the maximal number of characters
if (strlen($value) > $this->maxLength) {
//Error max length exceeded
}
}
} else {
if (!$this->allowNull) { //allowNull being a boolean: true if text can be empty
//Error value is empty
}
}
if(isset($this->regex)&&$this->regex!= ""){ //regex can be any regular expression, e.g: /[A-Za-z]/ for letters only
if(!preg_match($this->regex, $value)){
//Error value does not match expression
}
}
}
As far as XSS goes, make sure you use prepared statements when interacting with a database and use htmlentities when displaying user inputted data.
Hope this helps.
Some time ago, i've written a lightweight-validation class. Maybe you can use it.
For example:
$oValidator = new Validator();
$oValidator->setLanguage('en');
$oValidator->isValid('short description', 'max_length[4]');
echo $oValidator->getLastErrorMessage();
//The input can not exceed 4 characters in length.
$oValidator->isValid('min description', 'min_length[5]');
$oValidator->isValid('hello world. This is à ö text input :P :) :S :$ =D !! ??', 'min_length[5]');
$oValidator->isValid('1234567890', 'digits');
Rule definition:
/**
* #ErrorMessage[lang=de] Die Eingabe muss mindestens %d Zeichen lang sein.
* #ErrorMessage[lang=en] The input must be at least %d characters in length.
*/
public function check_min_length($mValue, $aParams)
{
return (strlen($mValue) >= $aParams[0]);
}
Example:
http://sklueh.de/2013/01/lightweight-php-validator-neue-version/
github:
https://github.com/sklueh/Lightweight-PHP-Validator

Mobile Phone Validation - Php

Apologies to bother you with a question that may seem quite blunt to some of you but I was wondering if any of you could shed some light on the validation side of things
Ive got a text field and I need validation on a mobile number so i need to validate that it has +44 at the beginning and including the +44 that it is 13 digits long , I found a few different techniques but nothing that defined it step by step only just copy and paste , Id like to learn how to do it so I know for future reference.
Any help would be appreciated
Thanks
Although this can be done simply with PHP string functions, I would urge you take this opportunity to learn regular expressions. Once you are ready you can use PHP PCRE functions to apply that regular expression.
Note: This answer is intentionally generalized in the interest of teaching a man to fish, per the OP request. I encourage posting a separate, more specific question after reviewing these resources.
Easy way:
php code:
if (isset($_POST['send'])) {
$mobile = $_POST['mobilenumber'];
// get the first 3 string
$begin = substr($mobile,0,3);
// get the rest of the posted string and add it to 0 to make it to number
// 'intval($variable)' and '(int) $variable' do the same
$theOthers = 0+substr($mobile,3);
// OR $theOthers = intval(substr($mobile,3));
// OR $theOthers = (int) substr($mobile,3);
$ok = true;
echo strlen($mobile);
// check the first 3 string
// if it's not equal with "+44", the entry is wrong
if ($begin != "+44") {
$ok = false;
} else {
// check the length of the input
// if it's not equal with 13, the entry is wrong
if (strlen($mobile)!=13) {
$ok = false;
}
}
if ($ok) {
// do something
}
}
html code:
<form method="post">
<input type="text" name="mobilenumber" maxlength="13" value="+44">
<input type="submit" name="send" value="Send">
</form>

Comparing string - woes in PHP

I want to allow the user to enter a coupon number in order to get a discount. After the coupon number is entered and submitted, the page reloads withe a tick showing that they have entered a correct amount.
The way I'm trying to do this is displaying the tick if the coupon amount is not £0.00. But the string comparison doesn't seem to work, since it always thinks that it is not £0.00. The code is as follows. The function coupon_amount() returns the coupon amount. coupon_amount() returns "£0.00" (including the pound sign)
<?php $coup_amount = coupon_amount(); ?>
<?php $zero_amount = "£0.00"; ?>
<?php if(strcmp($coup_amount, $zero_amount)== 0) { ?>
<?php echo 'Enter coupon code if applicable:' ?>
<input type='text' class='couponinput' name='coupon_num' id='coupon_num' value='coupons_name' />
<input type='submit' class='update-button' value='submitcoupon' />
<?php } else { ?>
<?php echo 'Thanks.' ?><input type='text' disabled='disabled' class='couponinput' name='coupon_num' id='coupon_num' value='coupons_name' />
<div class='tick'></div>
<?php } ?>
Am I doing something wrong with the comparison?
I followed Oscar's suggestion below, and here is the output. Seems to be an encoding problem. And the pound sign is not appearing properly for the zero_amount.
coup_amount: (£0.00) zero_amount: (�0.00)
coup_len:10 zero_len:5
strcmp: -1
coup_ascii: 38 zero_ascii:163
You should really be storing/working with the discount values as numbers, this would make the comparison much easier.
Have you tried printing out all the values?
<?php $coup_amount = coupon_amount(); ?>
<?php $zero_amount = "£0.00"; ?>
//print'em out
<pre>
<?php
echo "coup_amount: ($coup_amount) zero_amount: ($zero_amount) \n";
echo "coup_len:".strlen($coup_amount)." zero_len:".strlen($zero_amount)."\n";
echo "strcmp: ".strcmp($coup_amount, $zero_amount)."\n";
echo "coup_ascii: ".ord($coup_amount[0])." zero_ascii:".ord($zero_amount[0]);
?>
</pre>
Amendment
So yes, now that we can see the output from this, it seems like the coup-string is an UTF16 (10 bytes long) and the other is something else (5 bytes long).
(Preaching follows.) When dealing with money you should really take extra care to make sure numbers are handled correctly. We've just seen that strings are subject to encoding, and like others have pointed out, floats are subject to fractional errors. Your best bet is probably to try and express it in 1/100s using an integer, and to express the currency in a separate variable. (Preaching over.)
But I'm guessing the coupon_amount-function is used everywhere and you can't change it. Then you might wanna look into converting the two strings so that the are in the same format. Take a look at iconv.
<?php if(strcmp($coup_amount, $zero_amount)== 0) { ?>
Seems very unreadable compared to:
<?php if(coupon_amount() == 0) { ?>
If coupon_amount() returned the actual value, not the formatted string representation.
Are you able to change the coupon_amount() function to get rid of the pound symbol? the php function money_format is good for adding whatever the users currency symbol is to a string for displaying on the page (or which ever symbol you set the locale to)
In the future you will find yourself having to remove the pound symbol first before you do any arithmetic on the return value from coupon_amount()
There are a lot of things that seem insignificant to user, but may break string comparison
coupon_amount() may insert some spaces somewhere in returned value
coupon_amount() may return variable number of zeros
coupon_amount() may use comma instead of dot (depending on locale)
coupon_amount() may encode pound sign using some HTML entity
Said that, it is much better to compare numeric values, and then format number as currency.
the strcmp call seems ok, my bet is on the coupon_amount function.
The absurd lengths I had to go to to get this working :) .. I changed the first if statment to:
if((ord($coup_amount[0])==38) && (ord($coup_amount[1])==35)
&& (ord($coup_amount[2])==49) && (ord($coup_amount[3])==54)
&& (ord($coup_amount[4])==51) && (ord($coup_amount[5])==59)
&& (ord($coup_amount[6])==48) && (ord($coup_amount[7])==46)
&& (ord($coup_amount[8])==48) && (ord($coup_amount[9])==48)
&& (ord($coup_amount[10])==0))
have you triend comparing it without a pound sign?..
like this
substr($coup_amount, 1) == "0.00";
i see you're having problem when retrieving the pound sign so i think it is best to try this.

Categories