Check if user enters numbers ONLY, PHP - php

I have this inupt field
<p style="font-size: 18px;">Total Bids: <input type="text" class="total_bids" name="total_bids" placeholder="No. of Bids"></p>
getting its value via:
var totalbids = document.getElementsByName('total_bids')[0].value;
and getting the value in PHP via
$total_bids = PSF::requestGetPOST('totalbids');
Everything working fine, but it is supposed to take number value ONLY, so I am trying to check if user only enters a number, how can I define alphabet range so that I can set the check something like
if( $total_bids== 'alphabet range')
{
return json_encode(array('error' => 'Please enter a valid Number.'));
}

You can use RegEx and the \d Expression. \d matches only numbers.

First of all, you could disallow the person to enter anything but numbers in the <input../> by defining it's type as type="number".
Obviously, people could go around it so you still need to check it in the backend for that, you'll need to use a function like is_numeric().

You can check by is_numeric
if(!is_numeric($total_bids))
{
return json_encode(array('error' => 'Please enter a valid Number.'));
}
Also if you want do any special checks, you can use regexp by preg_match, for example:
if(!preg_match('~^[\d\.]$~', $total_bids))
{
return json_encode(array('error' => 'Please enter a valid Number.'));
}
Regexp more flexible, you can add your own rules to check by regexpm but is_numeric check faster then regexp check

if(preg_match ("/[^0-9]/", $total_bids)){
return json_encode(array('error' => 'Please enter a valid Number.'));
}

as per your input if you need only numbers then try ctype_digit:
$strings = array('1820.20', '10002', 'wsl!12');//input with quotes is preferable.
foreach ($strings as $testcase) {
if (ctype_digit($testcase)) {
echo "The string $testcase consists of all digits.\n";
} else {
echo "The string $testcase does not consist of all digits.\n";
}
}
see here :http://php.net/ctype_digit

Related

Use of Preg_match to Determine Mobile Number or Email

I'm asking if there are better ways of determining what string has been inputted, either a phone number or an email, here are my already working code
public function InviteFriend($invitation)
{
// Initialize Connection
$conn = $this->conn;
// Check what type of Invitation it is
if (preg_match_all('~\b\d[- /\d]*\d\b~', $invitation, $res) > 0) {
$type = 'phone';
} else if (preg_match_all('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/i', $invitation, $res) > 0) {
$type = 'email';
}
echo $type;
}
But my concern is if a user typed both phone and email in the same string, which of the if statement would be picked and which would be ignored? and is my way of determining which type of string proper or is there a more efficient way?
Thanks
There are two anchors almost available in all regex flavors which you have used in your second regex for validating an email address, shown as ^ and $ and meant as beginning and end of input string respectively.
You should use them for first validation as well. Your phone number validation lacks a good validation since it validates an arbitrary sequence of strings like 1------- --------5 that doesn't look like a phone number and much more things since it doesn't match against whole string (missing both mentioned anchors). So I used \d{10} to indicate a 10-digit phone number that you may want to change it to meet your own requirements, this time more precisely.
You don't really want that kind of email validation either. Something more simpler is better:
public function InviteFriend($invitation)
{
if (preg_match('~^\d{10}$~', $invitation)) {
$type = 'phone';
} else if (preg_match('~^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$~i', $invitation)) {
$type = 'email';
}
echo $type ?? 'Error';
}

Regular expression to check repeating character or digit, check lowercase,uppercase,capital

please help me..i'm stuck in here..
What i actually want is to check the password from repeating single character or digit.
Requirement for repeating
aaaa = false,
abbb = false
abag = false
a33f = false
abcd1234 = true
there is only once for a character should have in password. If more than once repeated, error returns. So hard to explain.
this is my draft code.
1)first i need to check whether the global configuration for repeating character is allowed or not, if yes my password can have repeating char or digit otherwise it would't. After this, i need to check whether the global configuration for lowercase,uppercase or capitals allowed or not.
if($globalCOnf['repeat_pass']=="yes")//allowed
{
//do nothing
}
else //not allowed
{
//stuck here :(
if(preg_match('/(.)\1{1,}/',$user_input_pass)) //only check "aaaa" not "aba"
{
echo "change password";
}
else
{
if($globalCOnf['having_lower_upper_capital']=="yes")//allowed
{
//do nothing
}
else
{
// can't continue
}
}
}
You can use array_count_values for this (An alternate regex free solution)
<?php
$password = 'abcdfa';
if(max(array_count_values(str_split($password)))>1)
{
echo "Choose another password as words you can't have repeatable characters";
}
OUTPUT:
Choose another password as words you can't have repeatable characters
You get that output because a is repeated two times.
Answer for the question.
if($globalCOnf['repeat_pass']=="yes")//allowed
{
//do nothing
}
else //not allowed
{
if(max(array_count_values(str_split($user_pass)))>1)
{
echo "change your password now!!!";
}
else
{
if($globalCOnf['having_lower_upper_capital']=="yes")//allowed
{
//do nothing
}
else
{
if(preg_match('/[A-Z]/', $user_pass))
{
echo "Can't use uppercase";
}
}
}
}
100% working.. :)
Try something like this -
(\d+).*\1
If you get any match there is a repeated character.
Just allow zero or more characters between two duplicate characters. If there is a match, then the string failed to pass the validation.
Code: (Demo)
$passwords=['aaaa','abbb','abAg','a33f','abcd1234'];
foreach($passwords as $pass){
echo "$pass: ";
if(!preg_match('/([a-zA-Z\d]).*\1/',$pass)){
echo "valid\n";
}else{
echo "failed\n";
}
}
Output:
aaaa: failed
abbb: failed
abAg: valid
a33f: failed
abcd1234: valid
Or as one-line: echo preg_match('/([a-zA-Z\d]).*\1/',$pass)?'failed':'valid'
Using this type of pattern is much more direct that generating a temporary array of characters and counting their occurrences and checking the highest count.

Find first position where pattern matching failed.

i am trying to find the common errors users have while entering email ids. I can always validate EMAIL using PHP Email Filter
$email = "someone#exa mple.com";
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo "E-mail is not valid";
}
else
{
echo "E-mail is valid";
}
or pattern matching
$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
I agree that these are not full proof ways to validate emails. However they should capture 80% of cases.
What I want is - Which position email became invalid? if its a space, at what position user had entered space. or did it fail because of "." in the end?
Any pointers?
-Ajay
PS : I have seen other thread regarding email validations. I can add complexity and make it 100%. concern here is to capture the most common mistakes made by people when entering Email ID.
This is difficult because sometimes it's not always a single character that makes an email address invalid. The example you give could easily be solved by:
$position = strpos('someone#exa mple.com', ' ');
However, it seems you are not interested in an all encompassing solution but rather something that will catch the majority of character based errors. I would take the approach of using the regular expression but capture each section of the email address in a sub pattern for further validation. For example:
$matches = null;
$result = preg_match("/(([\w\-]+)\#([\w\-]+)\.([\w\-]+))/", $email, $matches);
var_dump($matches);
By capturing sections of the regex validation in sub patterns you could then dive further into each section and run similar or different tests to determine where the user went wrong. For example you could try and match up the TLD of the email address against a whitelist. Of course there are also much more robust email validators in frameworks like Zend or Symfony that will tell you more specifically WHY an email address is not valid, but in terms of knowing which specific character position is at fault (assuming it's a character that is at fault) I think a combination of tactics would work best.
There is no way I know of in Java to report back the point at which a regex failed. What you could do is start building a set of common errors (as described by Manu) that you can check for (this might or might not use regex expressions). Then categorize into these known errors and 'other', counting the frequency of each. When an 'other' error occurs, develop a regex that would catch it.
If you want some assistance with tracking down why the regex failed you could use a utility such as regexbuddy, shown in this answer.
Just implement some checks on your own:
Point at the end:
if(substr($email, -1) == '.')
echo "Please remove the point at the end of you email";
Spaces found:
$spacePos = strpos($email, ' ');
if(spacePos !== false)
echo "Please remove the space at pos: ".$spacePos;
And so on...
First of all, I would like to say that the reason your example fails is not the space. It is the lack of '.' in former part and lack of '#' in the latter part.
If you input
'someone#example.co m' or 's omeone#example.com', it will success.
So you may need 'begin with' and 'end with' pattern to check strictly.
There is no exist method to check where a regular expression match fails as I know since check only gives the matches, but if you really want to find it out , we can do something by 'break down' the regular expression.
Let's take a look at your example check.
preg_match ("/^[\w\-]+\#[\w\-]+\.[\w\-]+$/",'someone#example.com.');
If it fails, you can check where its 'sub expression' successes and find out where the problem is:
$email = "someone#example.com.";
if(!preg_match ("/^[\w\-]+\#[\w\-]+\.[\w\-]+$/",$email)){ // fails because the final '.'
if(preg_match("/^[\w\-]+\#[\w\-]+\./",$email,$matches)){ // successes
$un_match = "[\w\-]+"; // What is taken from the tail of the regular expression.
foreach ($matches as $match){
$email_tail = str_replace($match,'',$email); // The email without the matching part. in this case : 'com.'
if(preg_match('/^'.$un_match.'/',$email_tail,$match_tails)){ // Check and delete the part that tail match the sub expression. In this example, 'com' matches /[\w\-]+/ but '.' doesn't.
$result = str_replace($match_tails[0],'',$email_tail);
}else{
$result = $email_tail;
}
}
}
}
var_dump($result); // you will get the last '.'
IF you understand the upper example, then we can make our solution more common, for instance, something like below:
$email = 'som eone#example.com.';
$pattern_chips = array(
'/^[\w\-]+\#[\w\-]+\./' => '[\w\-]+',
'/^[\w\-]+\#[\w\-]+/' => '\.',
'/^[\w\-]+\#/' => '[\w\-]+',
'/^[\w\-]+/' => '\#',
);
if(!preg_match ("/^[\w\-]+\#[\w\-]+\.[\w\-]+$/",$email)){
$result = $email;
foreach ($pattern_chips as $pattern => $un_match){
if(preg_match($pattern,$email,$matches)){
$email_tail = str_replace($matches[0],'',$email);
if(preg_match('/^'.$un_match.'/',$email_tail,$match_tails)){
$result = str_replace($match_tails[0],'',$email_tail);
}else{
$result = $email_tail;
}
break;
}
}
if(empty($result)){
echo "There has to be something more follows {$email}";
}else{
var_dump($result);
}
}else{
echo "success";
}
and you will get output:
string ' eone#example.com.' (length=18)

check string function

I am currently trying to get my head around some basic php string functions. I currently use this code which determines if the username entered in long enough e.g.:
if (strlen($_GET['name']) < 3) {
echo 'First Name should be at least 3 characters long!';
exit;
}
And this works just fine. Which string function should I use though if I want to to check on a specific name? E.g. I would like to trigger a message once someone enters a specific Word in the form field.
Some expert advice would be greatly appreciated.
This link of 60 PHP validation functions is an excelent resource.
For your case as to check a name, you could use something like:
if (strtolower($_GET['name']) === 'joe') {
// Do something for Joe
}
elseif (in_array(strtolower($_GET['name']), array('dave', 'bob', 'jane')) {
// Do something else for Dave, Bob or Jane
}
The strtolower will ensure that upper, lower or mixed case names will match.
You don't need a function for that. You can use a if statement and ==:
if ( $_GET['name'] == 'Dave' )
{
// user entered 'Dave'
}
if statement, or if you plan to check against multiple names, switch().
switch($_GET['name']){
case "Eric":
//Eric
break;
case "Sally":
//Sally
break;
case "Tom":
//Tom
break;
default:
//Unknown
}
Its good practice to check that $_GET['name'] is set before using. To answer your question a good way IMO is in_array(needle,haystack)
<?php
if (!empty($_GET['name']) && strlen($_GET['name']) < 3) {
echo 'First Name should be at least 3 characters long!';
exit;
}
//From a database or preset
$names = array('Bob','Steve','Grant');
if(in_array($_GET['name'], $names)){
echo 'Name is already taken!';
exit;
}
?>
You can use strstr or stristr(case-insensitive) function, If want to search for specific word in a sentence.
Just check php mannual for strstr, and stristr.

Phone number validating in php

I would like to "validate" my posted phone number. I don't really care about the format, i just want to use only numbers and some chars.
I tried this code, but if i type at least one number to my string then string will be valid. (for ex.: asdafadas-1asd will be valid)
How to fix this?
$phonebool=true;
if (!(strcspn($_POST['phone'], '0123456789-/ ') != strlen($_POST['phone']) )){
$_SESSION['phone_err']='Only numbers and -/';
$phonebool=false;
}
thank you.
You should use a regular expression instead, something like:
/^[0-9\/-]+$/
Otherwise have a look at libphonenumber - it seems that a php port exists: https://github.com/davideme/libphonenumber-for-PHP
Examples:
var_dump(preg_match('/^[0-9\/-]+$/', 'asdafadas-1asd'));
=> int(0)
var_dump(preg_match('/^[0-9\/-]+$/', '12/34-56'));
=> int(1)
Try This .
if(ereg("^[0-9]{3}-[0-9]{3}-[0-9]{4}$", $number) ) {
echo "works";
} else {
$errmsg = 'Please enter your valid phone number';
}
Working code
if (!(preg_match("([0-9-]+)", $_POST['phone']) != strlen($_POST['phone']) )){
$_SESSION['phone_err']='Only numbers and -/';
$phonebool=false;
}
one recommendation: use javascript/jquery to validate your forms, so the users can correct right away before submit.
Try this:
$phonebool=true;
if (!(preg_match("([0-9-]+)", $_POST['phone']) != strlen($_POST['phone']) )){
$_SESSION['phone_err']='Only numbers and -/';
$phonebool=false;
}

Categories