How to count integer values stored in a variable using php? - 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
}

Related

IE11 and input type="number"

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

how to make a field can not be filled minus or symbol?

So like normal field input, This filed should be filled only by numbers or letters, can not insert like symbol(~!##$/%^&-+=|*.\,) and minus numbers in PHP/html. Can help me please? i done search in internet not found only found for sql or vb
<input type="text" name="text" value="">
where this field will be POST to another php
$name =trim($_POST['name']);
Use this:
bool ctype_alnum ( string $text )
You could use alnum method of respect/validation:
if(v::alnum()->validate($stringToCheck)){
//valid
}
else {
//not valid
}

How to make user enter only positive numeric value for factorial

I want users to enter only positive number to calculate factorial not alphabets and not negative numbers in form of html in php as i am new to php , how can i?
<div id="mydiv">
<?php if(isset($_POST['fa']))
{ $val = $_POST['factori']; $valu=$val-1; while ( $valu!=1 )
{ $val=$valu*$val; $valu--; } }
?>
<form method="post" action=""> <h2>Calculate factorial for any number<br></h2>
If you want to forbid people to enter negative numbers in your client (front-end) then you must use JavaScript to listen to changes in the input area and you must validate them using regex (or simply by checking if the input value is negative or not), you can give certain warning messages and make the submit form become invalid.
Another approach is just to allow the user to post any numeric value to your back-end (PHP) and there you can simply check if the value is legit, if it's not legit you can simply return the error instead of of the calculated value.
Make an attempt to solve the problem and come back to us if you hit a wall.
Do it this way, check if number is numeric and > 0
<div id="mydiv">
<?php
if(isset($_POST['fa']))
{
$val = $_POST['factori'];
if(is_numeric($val) && $val > 0) // check if input is numeric and > 0
{ //valid input
$valu=$val-1;
while ( $valu!=1 )
{
$val=$valu*$val; $valu--;
}
}
else
{
// input is not numeric or is < 0
}
}
?>
<form method="post" action=""> <h2>Calculate factorial for any number<br></h2>

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

Categories