Disabling some characters with preg_match - php

I'm having an issue with my register page, i noticed that people can register with alt codes like this "ªµµª" and i tried to fix it by using preg_replace but when i did that i couldn't register anymore, atleast not with the worldwide alphabet
final public function validName($username)
{
if(strlen($username) <= 25 && ctype_alnum($username))
{
return true;
}
return false;
}
Tried to fix it by replacing it with this
if(strlen($username) <= 25 && preg_match("/[^a-zA-Z0-9]+/", $username))
But i'm obviously doing something wrong...

Apparently, you are confusing two different uses of the caret (^) metacharacter.
Indeed, it may be two things in a regular expression:
It may assert the start of the subject, which is what you probably want.
It may negate the class, which is what you're doing in your code.
Source: http://php.net/manual/en/regexp.reference.meta.php
Here is a modified version of your code, with the caret (^) and dollar ($) signs to assert the start and the end of the strings you're analyzing:
function validName($username)
{
if (strlen($username) <= 25 && preg_match("/^[a-zA-Z0-9]+$/", $username))
{
return true;
}
return false;
}
$names = array(
'Abc1',
'Abc$',
"ªµµª"
);
foreach ($names as $name) {
echo "<br>" . $name . ': ' . (validName($name) ? 'valid' : 'invalid');
}
// -- Returns:
// Abc1: valid
// Abc$: invalid
// ªµµª: invalid
Note that you may reduce the code inside your function to one line:
function validName($username)
{
return strlen($username) <= 25 && preg_match("/^[a-zA-Z0-9]+$/", $username);
}

Related

How to remove everything but allow letter, number and underscore?

How to remove everything but allow letter, number and underscore only in my validation for the username? I tried this code but it allows space:
function customUsername($username)
{
if (!preg_match('/^[a-z.,\-]+$/i',$username))
{
$this->form_validation->set_message('customUsername', 'The username field');
}
}
Use the following regex
function customUsername($username)
{
if (!preg_match('/^[a-zA-Z0-9_]+$/i',$username))
{
$this->form_validation->set_message('customUsername', 'The username field');
}
}
You can use ASCII code of every letter, number and underscore.
follow this link for ASCII code http://ascii.cl/ .
jQuery is like this.
$('#keyId').keydown(function(e){
var key = e.charCode || e.keyCode || 0;
return (
key == 8 ||
(key >= 23 && key <= 105)
);
});
So Simple It allow only Alphanumeric and Underscore only
<?php
$str='fdfdf5_';
if(preg_match('/^[a-zA-Z0-9_]+$/',$str))
{
echo "success";
}
else
{
echo "failed";
}
?>

Validate password policy with PHP preg_match

I'm trying to validate a password using preg_match and RegEx but it doesn't seem to work. What I want to do is: ensure the password meets the following minimal conditions:
- Contains mixed case letters
- Contains atleast one number
- The rest can be anything as long as the two conditions above are met.
I've tried the following RegEx but it doesn't seem to work properly:
(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])
I've had other previous easier RegEx'es like: [A-Za-z0-9] but without success. I'm checking if preg_match($string, $pattern) == 0 (meaning the pattern doesn't match => validation fails) but it always returns 0. What am I doing wrong ?
Just add a starting anchor to your regex,
^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])
OR
^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9]).*
Example:
$yourstring = 'Ab';
$regex = '~^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])~m';
if (preg_match($regex, $yourstring)) {
echo 'Yes! It matches!';
}
else {
echo 'No, it fails';
} // No, it fails
I always try to avoid regex if it's possible so I took a different approach to the problem. The below code will test the password for at least one uppercase, one lowercase and one digit.
function isValidPassword($password)
{
$hasUppercase = false;
$hasLowercase = false;
$hasDigit = false;
foreach (str_split($password) as $char)
{
$charAsciiValue = ord($char);
if ($charAsciiValue >= ord('A') && $charAsciiValue <= ord('Z')) {
$hasUppercase = true;
}
if ($charAsciiValue >= ord('a') && $charAsciiValue <= ord('z')) {
$hasLowercase = true;
}
if ($charAsciiValue >= ord('0') && $charAsciiValue <= ord('9')) {
$hasDigit = true;
}
}
return $hasUppercase && $hasLowercase && $hasDigit;
}
var_dump(isValidPassword('Ab9c'));
var_dump(isValidPassword('abc'));
Output
bool(true)
bool(false)
I offer a different solution, mainly because regexp provides little error reporting, and you would have to manually test the string afterwards anywhay for cohesion. Consider breaking the patterns apart and adding their own error. Iterate each of the requirements, and test the pattern. Push errors into an array and check after for their existence. Return a predeclared variable as true/false for the purpose of validating using if(validate_password($pass)):. Here's the mockup:
function validate_password($pass){
$requirements = array();
//uppercase
$requirements['uppercase']['pattern'] = '/[A-Z]/';
$requirements['uppercase']['error'] = 'Your password must contain at least one uppercase letter.';
//lowercase
$requirements['lowercase']['pattern'] = '/[a-z]/';
$requirements['lowercase']['error'] = 'Your password must contain at least one lowercase letter.';
//requires a number
$requirements['number']['pattern'] = '/[0-9]/';
$requirements['number']['error'] = 'Your password must contain at least one number.';
//special characters
$requirements['special_character']['pattern'] = '/[!##$%^&*()\\-_=+{};\:,<\.>]/';
$requirements['special_character']['error'] = 'Your password must contain at least one special character.';
//length
$requirements['length']['pattern'] = '/^.{8,}/';
$requirements['length']['error'] = 'Your password must be at least 8 characters in length total.';
$is_valid = false; //our flag to return as true once all tests have passed.
$errors = false;
//validate all requirements
foreach($requirements as $idx => $req):
if(preg_match($req['pattern'], $pass, $matches)):
$is_valid = true;
else:
$errors[] = $req['error'];
$is_valid = false;
endif;
endforeach;
//if we had errors above
if($errors):
$is_valid = false;
foreach($errors as $error):
echo '<p>', $error, '</p>';
endforeach;
endif;
return $is_valid;
}
$pass = 'j!Adz6'; //change this to test
echo validate_password($pass);
And an eval.in example for your pleasure.

check if numeric php

my problem is, i have a form which i fill blabla and after i submit i need to check if the var '$number' contains only 9 numbers. which means that if it contains at least 1 letter or has less or more than 9 length it should return false, else it should return true;
this is what i got so far:
if (!is_numeric ($number) {
//do
} else {
}
1st problem: This code should take care of the only numbers part but it doesnt, it always returns false.
2nd: do you guys know of any way to take care of the 9 digits only verification?
thanks and sorry for my bad english, not my native language :P
Your number may contain unwanted whitespaces which cause the is_numeric() test not to work properly
So do the following: $number = trim($number); to remove them.
Then indeed this snippet is good to check if your variable is a number:
if (!is_numeric ($number)) {
//do
} else {
}
And for the number digits do a if statement to see if your number is between 100000000 and 999999999
So the full code will be:
$number = trim($number);
if (!is_numeric ($number)) {
//do
} else {
if ($number >= 100000000 && $number <= 999999999) {
// Everything is ok
} else {
}
}
Didn't understood your complete question coz of you native language :p, but i think you want this:
if (is_numeric($number) {
if(strlen($number) == 9){
return true;
} else {
return false;
}
} else {
echo 'Not a number';
}
Check if it contains digits and check whether its exactly contains 9.
$number = '123456789';
if(!preg_match('/^\d{9}$/', $number)) {
echo 'not ok';
} else {
echo 'ok';
}

PHP -> REGEX | password validation not working

I use this (almost) complex password verification:
function is_password($password) {
return preg_match("^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20}$", $password);
}
So it must contain:
one digit from 0-9,
one lowercase character,
one uppercase character,
at least 6 characters
at most 20 characters
This does not seem to work. Whenever I type certain characters like e, t, o, j, c and b; the function returns true if allowed length is correct. So uppercase and digit is not being validated..
What am I doing wrong?
You forgot to use delimiters. Use this code instead:
return preg_match("/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20}$/", $password);
Or you may split each condition and use this code:
return mb_strlen($password)>=6 && mb_strlen($password)<=20
&& preg_match("/[a-z]+/", $password) && preg_match("/[A-Z]+/", $password)
&& preg_match("/[0-9]+/", $password);
I would break this apart into multiple checks. This will allow you to intelligently give feedback to the user (or to a log) as to why the password selection failed.
<?php
function is_password($password){
if (strlen($password) < 6) {
// too short
return false;
}
if (strlen($password) > 20) {
// too long
return false;
}
if (!preg_match("/[A-Z]/", $password) {
// no upper
return false;
}
if (!preg_match("/[a-z]/", $password) {
// no lower
return false;
}
if (!preg_match("/[0-9]/", $password) {
// no digit
return false;
}
return true;
}
?>

Function to validate username and password not working [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Regular Expression matching for entire string
On my form page, I am trying to make it only accept alphanumeric characters for my username and password and require that they be from 6 to 15 characters. When I type in invalid data, it will insert it into the database rather than throw the user error that I defined in my CheckAlNum function.
functions.php
function checkAlNum($whichField)
{
if (preg_match('/[A-Za-z0-9]+/', $_POST[$whichField])){
if ( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 ))) {
$message1 = '<p> Username and password must be between 6 and 15 characters </p>';
return user_error($message1);
}
else{
return true;
}
}
else {
$message = '<p>Username and password can only be numbers or letters</p>';
return user_error($message);
}
}
Form.php
if (count($_POST) > 0) {
//Validate the inputs
$errorMessages = array();
//Validate the username
$item5 = checkAlNum('username');
if($item5 !== true) {
$errorMessages[] = $item5;
}
//Validate the password
$item6 = checkAlNum('password');
if($item6 !== true) {
$errorMessages[] = $item6;
}
//Validate the firstName and lastName
$item1 = checkNameChars('firstName');
if ($item1 !== true) {
$errorMessages[] = $item1;
}
$item2 = checkNameChars('lastName');
if ($item2 !== true) {
$errorMessages[] = $item2;
}
//Validate the office name
$item3 = checkOfficeChars('office');
if ($item3 !== true) {
$errorMessages[] = $item3;
}
//Validate the phone number
$item4 = validate_phone_number('phoneNumber');
if($item4 !== true) {
$errorMessages[] = $item4;
}
//Check to see if anything failed
if (count($errorMessages) == 0) {
$newEmployee = new Person;
$newEmployee -> insert();
}
else { //Else, reprint the form along with some error messages
echo "<h2><span>Error</span>: </h2>";
foreach($errorMessages as $msg) {
echo "<p>" . $msg . "</p>";
}
}
}
?>
I've tried playing around with the nesting of the if-else statements of the checkAlNum function and also the regex (although I'm pretty sure the regex is right). Maybe I'm just missing something really silly?
function checkAlNum($whichField)
{
if (preg_match('/^[a-z0-9]{6,15}$/i', $_POST[$whichField])) {
return true;
}
else {
$message = '<p>Username and password can only be numbers or letters, 6-15 characters long</p>';
return user_error($message);
}
}
Without the ^ and $ anchors, your regex only checks whether there are alphanumerics anywhere in the field, not that the whole thing is alphanumeric. And changing + to {6,15} implements the length check here, so you can remove that extra check in your code.
I think the second if statement is incorrect. It should be like this:
if ( !( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 )) ) ) {
// ... do something
}
This is due to De Morgan Rule which states
A AND B = !( !A OR !B )
In any case, I would not do my checks this way, strucurally you will end up with too many nested if statements that are hard to maintain and make your code look unpretty. Try avoiding nested conditions in your code.
Barmar's answer is the best. But if you want to keep your if statement to check string length, you need to remove the count() as you are already checking the length using strlen().
if ( (!(strlen($whichField) >= 6)) OR (!(strlen($whichField) <= 15 ))) {

Categories