Skip to content

Instantly share code, notes, and snippets.

@fkling
Created April 15, 2010 20:43
Show Gist options
  • Save fkling/367623 to your computer and use it in GitHub Desktop.
Save fkling/367623 to your computer and use it in GitHub Desktop.
<?php
class fkValidatorPassword extends sfValidatorBase {
/**
* Configures the current validator.
*
* Available options:
*
* password: The password that is already set (required)
* pattern: A regex pattern or an array of regex patterns compatible with PCRE
* password_field: The name of the password field
* password_check_field: The name of the field to conpare the password with
*
* Available error codes:
* notequal
* invalid
* required
*
* @param array $options An array of options
* @param array $messages An array of error messages
* @see sfValidatorBase
*/
public function configure($options = array(), $messages = array()) {
$this->addRequiredOption('password', '');
$this->addOption('pattern',array());
$this->addOption('password_field', 'password');
$this->addOption('password_check_field', 'password_check');
$this->addMessage('notequal', 'Passwords are not euqal.');
}
protected function doClean($values) {
$defaultPassword = (string) $this->getOption('password');
$password = isset($values[$this->getOption('password_field')]) ?
$values[$this->getOption('password_field')] : '';
$password_check = isset($values[$this->getOption('password_check_field')]) ?
$values[$this->getOption('password_check_field')] : '';
$patterns = is_array($this->getOption('pattern')) ?
$this->getOption('pattern') : array($this->getOption('pattern'));
// check if a password is set in the form...
if(!empty($password)) {
if(!empty($patterns)) {
foreach($patterns as $pattern) {
if(!preg_match($pattern, $password)) {
throw new sfValidatorErrorSchema($this,
array($this->getOption('password_field') => new sfValidatorError($this, 'invalid')));
}
}
}
// verify password
if($password !== $password_check) {
throw new sfValidatorErrorSchema($this,
array($this->getOption('password_check_field') => new sfValidatorError($this, 'notequal')));
}
}
else { // no password set in the form, check if a password is already set...
if(empty($defaultPassword)) {
throw new sfValidatorErrorSchema($this,
array($this->getOption('password_field') => new sfValidatorError($this, 'required')));
}
else {
unset($values['password']);
}
}
return $values;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment