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;
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';
}
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.
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;
}
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 use the clas below to validate user input. Originally it was just a collection of static functions grouped together.
However, I modifed it to an object style and added in a private memeber to hold the user input array. What is the next step to making this class adaptable, i.e. more generic so that it can be used by others as part of a library?
$message is the text displayed to the user on a validation fail.
Library Code:
class validate
{
private $input;
function __construct($input_arg)
{
$this->input=$input_arg;
}
function empty_user($message)
{
if((int)!in_array('',$this->input,TRUE)) return 1;
echo $message;return 0;
}
function name($message)
{
if(preg_match('/^[a-zA-Z-\.]{1,40}$/',$this->input['name'])) return 1;
echo $message;return 0;
}
function email($message)
{
if(preg_match('/^[a-zA-Z0-9._s-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{1,4}$/',$this->input['email'])) return 1;
echo $message;return 0;
}
function pass($message)
{
if(preg_match('/^[a-zA-Z0-9!##$%^&*]{6,20}$/',$this->input['pass'])) return 1;
echo $message;return 0;
}
}
Application Code:
function __construct()
{
parent::__construct();
$obj=check_new($this->_protected_arr);
$a='<si_f>Please enter both an email and a password!';
$b='<si_f>Please enter a valid email!';
$c='<si_f>Please enter a valid password!';
if($obj->empty_user($a) && $obj->email($b) && $obj->pass($c) && self::validate())
{
self::activate_session();
echo "<si_p>";
}
}
I'd not write all these function in a generic class. I'd rather have separate functions that perform specific checks, and maybe a specific class that calls these checks on my specific input.
This class now echo's, which is never a good solution for a class like this. Just let it perform the check and raise an exception if something's wrong. If exceptions are too hard, or don't fit in your achitecture, let your function return false, and set a property that can be read afterwards.
About your specific checks:
Your e-mail check is very strict and doesn't allow all e-mail addresses. The domain, for instance, can be an IP address too, and the username (the part before the #) can include many obscure characters, including an #. Yes, really!
Why must a password be 6 characters at least? And why on earth would you limit the password to 20 characters? I use passwords of over 20 characters, and I know many other people that do too. Just let everybody type everything they want. Anything. Let them post 3MB of text if they like. Let them include unicode characters if they want. What is a better protection that having a bunch of chinese characters as a password? And if they want to enter just a, that's their responsibility too.
You should never ever store the password itself anyway, so just hash whatever they input and store the 32 characters that gives you (if you use MD5 hashing). The only password that you may refuse is an empty password. Anything else should go.
Same goes for name. 40 characters? Really. I can imagine people having names that long. Add a little more space. Bytes aren't that expensive, and it's not that you're gonna have 2 billion users.
Maybe it's worth having a look at Zend Validate? Or any other PHP frameworks validate classes. Just then extend them to add the functionality you want.
In answer to your question, is it worth having another variable in the class so you can check the error?
class validate
{
private $input;
public $error = false;
function __construct($input_arg)
{
$this->input=$input_arg;
}
function empty_user($message)
{
if((int)!in_array('',$this->input,TRUE)) return 1;
echo $message;$this->error = "Empty message";
}
... else
}
$validate = new validate($empty_message);
if( !$validate->empty_user('this input is empty') === false)
{
echo "Was not empty";
}