Created
July 27, 2021 20:28
-
-
Save Lschulzes/9c8a9392defd8215c88b62ecb40fc5b0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Rules { | |
// Sets all of the rules to check a given field | |
public $ruleParameters = ['isRequired', 'maxLenght', 'minLength', 'atLeastOne']; | |
// Creates all of the specific parameters for the rules | |
public function __construct($parameters){ | |
foreach($parameters as $parameter => $value) $this->ruleParameters[$parameter] = $value; | |
} | |
// Checks if a string follows all of the parameters | |
public function checkRules($string) { | |
$strLength = strlen($string); | |
if($this->ruleParameters['isRequired'] && !($strLength !== 0)) return false; | |
if($this->ruleParameters['maxLenght'] < $strLength || $this->ruleParameters['minLength'] > $strLength) return false; | |
if(!preg_match("/[" . $this->ruleParameters['atLeastOne'] . "]/" , $string, $matches)) return false; | |
// if it passes through it all, returns true | |
return true; | |
} | |
} | |
class Validator extends Rules { | |
// Calls the parent constructor method with the parameters passed in | |
public function __construct($params) { | |
parent::__construct($params); | |
} | |
// Checks if a given password follows a set of rules | |
public function checkPassword($password) { | |
return $this->checkRules($password); | |
} | |
} | |
// Creates a new instance of the validator class, with all of the parameters | |
$validator = new Validator([ | |
"isRequired" => true, | |
"maxLenght" => 20, | |
"minLength" => 6, | |
"atLeastOne" => " !\"#$%&'()*\+,-.\/:;<=>?@\[\]^_`{|}~", | |
]); | |
// If the validator method returns false, exits the program after refreshing the page and setting a session variable | |
if(!$validator->checkPassword($password)) { | |
header("Refresh:0"); | |
$_SESSION['password'] = 'wrong'; | |
exit; | |
} | |
?> | |
<div class="form-floating"> | |
<input name="password" type="password" class="form-control" id="floatingPassword" placeholder="Password"> | |
<label for="floatingPassword">Password</label> | |
<?php if(isset($_SESSION['password']) && $_SESSION['password'] == 'wrong') { | |
echo "<p style='color: #ee5a5a'>Password must contain 6 to 20 characteres and also a special char!</p>"; | |
// After echoing the error message resets the Session variable | |
unset($_SESSION['password']); | |
} | |
?> | |
</div> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
About youtube, that's a shame, it's pretty frustating, hope they'll fix it