I am having trouble with a text validation function. I need it to make sure a password has at least 1 number, one lowercase letter, one uppercase letter, no spaces, and one character that isn't a number or letter. My code so far:
function validatePassword($Password)
{
if (preg_match("/[!-/0-9A-Za-z]/", $Password)==1)
{
return TRUE;
}
else
{
return FALSE;
}
}
right now, it displays everything as invalid. I am also recieving the error:
"Warning: preg_match(): Unknown modifier '0' in /jail/home/ds0005/html/project1/p1s5.php on line 32"
If it helps, the rest of my code is listed below:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
$Passwords = array(
'Pas$word1',
'Pas$word2',
'Pas$word3',
'Pas$word4',
'pas$word1',
'PAS$WORD1',
'Password1',
'Pas$word',
'Pas$word 1',
'Pas$word1234567890',
'P$wd1');
function validatePassword($Password)
{
if (preg_match("/[!-/0-9A-Za-z]/", $Password)==1)
{
return TRUE;
}
else
{
return FALSE;
}
}
foreach ($Passwords as $Password)
{
if (validatePassword($Password) == false)
{
echo "<p>The password <em>$Password</em> does not appear to be valid.</p>";
}
}
echo "<p>Processing has completed.</p>";
?>
Any help would be greatly appreciated
Try this:
if (preg_match("/^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])[0-9A-Za-z!-\/]{1,}$/", $Password)==1)
See here for more info: https://stackoverflow.com/a/11874336/1512654
You might have to escape the forwardslash character like this:
preg_match("/[!-\/0-9A-Za-z]/", $Password)
Regexes aren't really the best tool for this kind of job, but here you go anyway.
Your requirements are literally expressed like so:
^(?=.*?\d)(?=.*?\p{Ll})(?=.*?\p{Lu})(?!.*?\s)(?=.*?[^\p{L}\d])
I think it'd be better to do these checks yourself without regex though.
<?php
if (!preg_match('/([a-z]{1,})/', $value)) {
// atleast one lowercase letter
}
if (!preg_match('/([A-Z]{1,})/', $value)) {
// atleast one uppercase letter
}
if (!preg_match('/([\d]{1,})/', $value)) {
// altelast one digit
}
if (strlen($value) < 8) {
// atleast 8 characters length
}
?>