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;
}
Related
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';
}
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
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.
I am new to PHP (not programming overall), and having problems with this simple line of code. I want to check whether some input field has been filled as anysymbolornumber#anysymbolornumber just for checking whether correct email was typed. I don't get any error, but the whole check system doesn't work. Here is my code and thanks!
if ($email = "[a-zA-Z0-9]#[a-zA-Z0-9]")
{
Since your new to php , i suggest you should buy a book or read an tutorial or two.
For email validation you should use filter_var an build in function that comes with with php 5.2 and up :
<?php
if(!filter_var("someone#example....com", FILTER_VALIDATE_EMAIL)){
echo("E-mail is not valid");
}else{
echo("E-mail is valid");
}
?>
you can use other functions .. instead of regular expressions
if(filter_var($email,FILTER_VALIDATE_EMAIL)){
echo "Valid email";
}else{
echo "Not a valid email";
}
As correctly pointed out in the comments, the regex you are using isn't actually a very good way of validating the email. There are much better ways, but if you are just wanting to get a look at how regular expressions work, it is a starting point. I am not an expert in regex, but this will at least get your if statement working :)
if(preg_match("[a-zA-Z0-9]#[a-zA-Z0-9]",$email)
{
// Your stuff
}
It looks like you're trying to verify that an email address matches a certain pattern. But you're not using the proper function. You probably want something like preg_match( $pattern, $target ).
Also, your regex isn't doing what you would want anyway. In particular, you need some quantifiers, or else your email addresses will only be able to consist of one character ahead of the #, and one after. And you need anchors at the beginning and end of the sequence so that you're matching against the entire address, not just the two characters closest to the #.
Consider this:
if( preg_match("^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+$", $email ) ) {
// Whatever
}
Keep in mind, however, that this is really a poor-man's approach to validating an email address. Email addresses can contain a lot more characters than those listed in the character class I provided. Furthermore, it would also be possible to construct an invalid email address with those same character classes. It doesn't even begin to deal with Unicode. Using a regex to validate an email address is quite difficult. Friedl takes a shot at it in Mastering Regular Expressions (O'Reilly), and his effort takes a 2KB regular expression pattern. At best, this is only a basic sanity check. It's not a secure means of verifying an email address. At worst, it literally misses valid regexes, and still matches invalid ones.
There is the mailparse_rfc822_parse_addresses function which is more reliable in detecting and matching email addresses.
You need to use preg_match to run the regular expression.
Now you're setting the $email = to the regular expression.
It could look like:
if ( preg_match("[a-zA-Z0-9]#[a-zA-Z0-9]", $email ))
Also keep in mind when matching in an if you must use the == operator.
I believe best pratice would be to use a filter_var instead like:
if( ! filter_var( $email , FILTER_VALIDATE_EMAIL )) {
// Failed.
}
Another way taken from: http://www.linuxjournal.com/article/9585
function check_email_address($email) {
// First, we check that there's one # symbol,
// and that the lengths are right.
if (!ereg("^[^#]{1,64}#[^#]{1,255}$", $email)) {
// Email invalid because wrong number of characters
// in one section or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if
(!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&
↪'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
$local_array[$i])) {
return false;
}
}
// Check if domain is IP. If not,
// it should be valid domain name
if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if
(!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|
↪([A-Za-z0-9]+))$",
$domain_array[$i])) {
return false;
}
}
}
return true;
}
I am having problem in validating email address with regular expression.The code is seems to works fine until user put some long characters separated by(.dot) at end.Code is
if(preg_match('~^\b[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-z]{2,4}+\b$~',$_POST["email"]))
{
$valid ="valid";
}
else
{
$valid ="invalid";
}
Problem comes when user put something like ksdlk#gll.lik.ij.lio.lk.gr it returns "valid". How to deal with last characters, that would only allow 4,5 characters from # like ".com"or ".co.uk".
Thanks in advance
Try to use this
if(filter_var('email#example.com', FILTER_VALIDATE_EMAIL))return TRUE;
else return FALSE;