/** * Ensures that the validator follows expected behavior * * @return void */ public function testBasic() { $valuesExpected = array('abc123' => true, 'abc 123' => false, 'abcxyz' => true, 'AZ@#4.3' => false, 'aBc123' => true); foreach ($valuesExpected as $input => $result) { $this->assertEquals($result, $this->_validator->isValid($input)); } }
/** * Ensures that the allowWhiteSpace option works as expected * * @return void */ public function testAllowWhiteSpace() { $this->_validator->allowWhiteSpace = true; $valuesExpected = array('abc123' => true, 'abc 123' => true, 'abcxyz' => true, 'AZ@#4.3' => false, 'aBc123' => true, '' => false, ' ' => true, "\n" => true, " \t " => true, 'foobar1' => true); foreach ($valuesExpected as $input => $result) { $this->assertEquals($result, $this->_validator->isValid($input), "Expected '{$input}' to be considered " . ($result ? '' : 'in') . "valid"); } }
public function init() { // валидаторы $alnum = new Zend_Validate_Alnum(); $alnum->setMessage($this->messageAlnum); $notEmpty = new Zend_Validate_NotEmpty(); $notEmpty->setMessage($this->notEmpty, "isEmpty"); // создаем форму $this->setName('interview'); $this->setAttribs(array('method' => "post", "class" => "form-horizontal")); $this->setDecorators(array('FormElements', 'Form')); $this->createFormElements($this, $this->elementsForm()); return $this; }
/** * @return void * @deprecated Since 1.5.0 */ public function testInvalidValueResultsInProperValidationFailureErrors() { $this->assertFalse($this->_validator->isValid('#')); $errors = $this->_validator->getErrors(); $arrayExpected = array(Zend_Validate_Alnum::NOT_ALNUM); $this->assertThat($errors, $this->identicalTo($arrayExpected)); }
public function init() { // валидаторы $alnum = new Zend_Validate_Alnum(); $alnum->setMessage($this->messageAlnum); $notEmpty = new Zend_Validate_NotEmpty(); $notEmpty->setMessage($this->notEmpty, "isEmpty"); // фильтры $stringTrim = new Zend_Filter_StringTrim(); $stripTags = new Zend_Filter_StripTags(); // добавляем элементы формы в массив, потом будем собирать форму в цыкле $elementsForm = array('surname' => array('type' => 'text', 'label' => 'ФИО', 'attribs' => array('class' => 'span12', 'placeholder' => 'Фамилия')), 'name' => array('label' => 'Имя', 'attribs' => array('class' => 'span12', 'placeholder' => 'Имя')), 'patronymic' => array('label' => 'Отчество', 'attribs' => array('class' => 'span12', 'placeholder' => 'Отчество')), 'sex' => array('type' => 'select', 'label' => 'Пол', 'multiOptions' => array('male' => 'Мужской', 'female' => 'Женский')), 'birthday' => array('label' => 'Дата Рождения', 'attribs' => $this->datepicker), 'maidenName' => array('label' => 'Девичья фамилия (если менялась)'), 'placeOfBirth' => array('label' => 'Место рождения (по паспорту)'), 'oldCountry' => array('label' => 'Страна рождения', 'attribs' => array('class' => 'span12')), 'nationality' => array('label' => 'Текущее гражданство', 'attribs' => array('class' => 'span12')), 'citizenship' => array('label' => 'Гражданство (при рождении)', 'attribs' => array('class' => 'span12')), 'FIFather' => array('label' => 'И.Ф Отца', 'attribs' => array('class' => 'span12')), 'FIMother' => array('label' => 'И.Ф Матери', 'attribs' => array('class' => 'span12')), 'maritalStatus' => array('type' => 'select', 'label' => 'Семейное Положение', 'multiOptions' => array('married' => 'женат/замужем', 'single' => 'холост/незамужем')), 'addressOfRegistration' => array('label' => 'Адрес (по прописке)'), 'telephoneNumber' => array('label' => 'Номер телефона'), 'profession' => array('label' => 'Профессия'), 'refsCompany' => array('label' => 'Назв. фирмы'), 'cityWhereTriesFirm' => array('label' => 'Город, где находится фирма'), 'workPhone' => array('label' => 'Раб телефон'), 'firstBorderCrossing' => array('label' => 'Первый пункт пересечения границы'), 'foreignPassport' => array('type' => 'text', 'label' => 'Данные заграничного пасспорта', 'attribs' => array('class' => 'span12', 'placeholder' => 'Серия и номер')), 'startDate' => array('type' => 'text', 'label' => 'Дата выдачи', 'attribs' => array('class' => 'span12 datepicker', 'readonly' => '', 'placeholder' => 'Дата выдачи')), 'endDate' => array('type' => 'text', 'label' => 'Дата окончания', 'attribs' => array('class' => 'span12 datepicker', 'readonly' => '', 'placeholder' => 'Дата окончания')), 'issued' => array('type' => 'text', 'label' => 'Кем выдан', 'attribs' => array('class' => 'span12', 'placeholder' => 'Кем выдан')), 'schengenVisasLast' => array('type' => 'textarea', 'label' => 'Шенгенские визы за последние 3 года', 'attribs' => $this->textareaAttribs), 'serNumPassport' => array('label' => 'Серия, номер гражданского паспорта'), 'addressActual' => array('label' => 'Адрес (фактический)'), 'theseSpouse' => array('type' => 'textarea', 'label' => 'Данные супруга(и)Девичья фамилия, дата рождения, место рождения', 'attribs' => $this->textareaAttribs), 'forMinors' => array('type' => 'textarea', 'label' => 'Для несовершеннолетних: ФИО, адрес и гражданство законного представителя', 'attribs' => $this->textareaAttribs), 'whoPays' => array('type' => 'select', 'label' => 'Кто оплачивает поездку', 'multiOptions' => array('myself' => 'Сам турист', 'sponsor' => 'Спонсор')), 'sponsor' => array('label' => 'Кто является спонсором')); // создаем форму $this->setName('interview'); $this->setAttribs(array('method' => "post", "class" => "form-horizontal")); $this->setDecorators(array('FormElements', 'Form')); $this->createFormElements($this, $elementsForm, $this->elementDecorators, $this->buttonLabel, $this->buttonDecorators); return $this; }
public function init() { $dbValidator = new Zend_Validate_Db_RecordExists(array('table' => 'users', 'field' => 'login')); $dbValidator->setMessage('Пользователя с таким именем нет в наших записях.'); $alnum = new Zend_Validate_Alnum(); $alnum->setMessage('Только буквы и цыфры!'); $notEmpty = new Zend_Validate_NotEmpty(); $notEmpty->setMessage('Поле обязательно для заполнения', 'isEmpty'); $stringLength = new Zend_Validate_StringLength(array('min' => 3)); $stringLength->setMessage('Длина поля должна быть больше трех символов.'); if (!empty($_GET['referer'])) { $referer = $_GET['referer']; } else { $referer = '/'; } $elementsForm = array('login' => array('type' => 'text', 'label' => 'Введите логин'), 'password' => array('type' => 'text', 'label' => 'Введите пароль', 'validators' => array('alnum' => $alnum, 'notEmpty' => $notEmpty, 'dbValidator' => $dbValidator, 'stringLength' => $stringLength)), 'redirect' => array('type' => 'hidden', 'attribs' => array('value' => $referer))); // имя формы; $this->setName('auth'); $this->setAttribs(array('method' => "post", "role" => "form", "class" => "form-horizontal")); $this->createFormElements($this, $elementsForm, $this->elementDecorators, 'Войти', $this->buttonDecorators); return $this; }
public function isValid($value) { $valueString = (string) $value; $this->_setValue($valueString); if ('' === $valueString) { $this->_error(self::STRING_EMPTY); return false; } if (null === self::$_filter) { require_once 'Zend/Filter/Alnum.php'; self::$_filter = new Zend_Filter_Alnum(); } self::$_filter->allowWhiteSpace = $this->allowWhiteSpace; if ($valueString !== self::$_filter->filter($valueString)) { $this->_error(self::NOT_ALNUM); return false; } return true; }
private function validateFormAndGetCRL(&$validationErrors) { $registry = Zend_Registry::getInstance(); $translate = $registry->get("Zend_Translate"); $validationErrors = array(); $crl = new SSLCRL(); $validate_alnum_wspace = new Zend_Validate_Alnum(array('allowWhiteSpace' => true)); // TODO: validate id field? $id = $_POST['crl_id']; $crl->setId($id); $name = $_POST['crl_name']; if (!$validate_alnum_wspace->isValid($name)) { $validationErrors['crl_name'] = $translate->translate("The CRL name must be only alpha-numeric characters"); } $crl->setDisplayName($_POST['crl_name']); if (isset($_FILES['crl_file']) && !empty($_FILES['crl_file']['name'])) { if (!$_FILES['crl_file']['error']) { $contents = file_get_contents($_FILES['crl_file']['tmp_name']); if ($contents !== false) { $crl->setContent($contents); } else { $validationErrors['crl_file'] = $translate->translate("There was an error getting contents of CRL file."); } } else { $validationErrors['crl_file'] = $translate->translate("There was an error uploading file: ") . $_FILES['content']['error']; } } else { if (empty($id)) { $validationErrors['crl_file'] = $translate->translate("Please upload a CRL file."); } } return $crl; }
/** * Validate value by attribute input validation rule * * @param string $value * @return string */ protected function _validateInputRule($value) { // skip validate empty value if (empty($value)) { return true; } $label = $this->getAttribute()->getStoreLabel(); $validateRules = $this->getAttribute()->getValidateRules(); if (!empty($validateRules['input_validation'])) { switch ($validateRules['input_validation']) { case 'alphanumeric': $validator = new Zend_Validate_Alnum(true); $validator->setMessage(Mage::helper('customer')->__('"%s" invalid type entered.', $label), Zend_Validate_Alnum::INVALID); $validator->setMessage(Mage::helper('customer')->__('"%s" has not only alphabetic and digit characters.', $label), Zend_Validate_Alnum::NOT_ALNUM); $validator->setMessage(Mage::helper('customer')->__('"%s" is an empty string.', $label), Zend_Validate_Alnum::STRING_EMPTY); if (!$validator->isValid($value)) { return $validator->getMessages(); } break; case 'numeric': $validator = new Zend_Validate_Digits(); $validator->setMessage(Mage::helper('customer')->__('"%s" invalid type entered.', $label), Zend_Validate_Digits::INVALID); $validator->setMessage(Mage::helper('customer')->__('"%s" contains not only digit characters.', $label), Zend_Validate_Digits::NOT_DIGITS); $validator->setMessage(Mage::helper('customer')->__('"%s" is an empty string.', $label), Zend_Validate_Digits::STRING_EMPTY); if (!$validator->isValid($value)) { return $validator->getMessages(); } break; case 'alpha': $validator = new Zend_Validate_Alpha(true); $validator->setMessage(Mage::helper('customer')->__('"%s" invalid type entered.', $label), Zend_Validate_Alpha::INVALID); $validator->setMessage(Mage::helper('customer')->__('"%s" has not only alphabetic characters.', $label), Zend_Validate_Alpha::NOT_ALPHA); $validator->setMessage(Mage::helper('customer')->__('"%s" is an empty string.', $label), Zend_Validate_Alpha::STRING_EMPTY); if (!$validator->isValid($value)) { return $validator->getMessages(); } break; case 'email': $validator = new Zend_Validate_EmailAddress(); $validator->setMessage(Mage::helper('customer')->__('"%s" invalid type entered.', $label), Zend_Validate_EmailAddress::INVALID); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid email address.', $label), Zend_Validate_EmailAddress::INVALID_FORMAT); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid hostname.', $label), Zend_Validate_EmailAddress::INVALID_HOSTNAME); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid hostname.', $label), Zend_Validate_EmailAddress::INVALID_MX_RECORD); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid hostname.', $label), Zend_Validate_EmailAddress::INVALID_MX_RECORD); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid email address.', $label), Zend_Validate_EmailAddress::DOT_ATOM); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid email address.', $label), Zend_Validate_EmailAddress::QUOTED_STRING); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid email address.', $label), Zend_Validate_EmailAddress::INVALID_LOCAL_PART); $validator->setMessage(Mage::helper('customer')->__('"%s" exceeds the allowed length.', $label), Zend_Validate_EmailAddress::LENGTH_EXCEEDED); if (!$validator->isValid($value)) { return array_unique($validator->getMessages()); } break; case 'url': $parsedUrl = parse_url($value); if ($parsedUrl === false || empty($parsedUrl['scheme']) || empty($parsedUrl['host'])) { return array(Mage::helper('customer')->__('"%s" is not a valid URL.', $label)); } $validator = new Zend_Validate_Hostname(); if (!$validator->isValid($parsedUrl['host'])) { return array(Mage::helper('customer')->__('"%s" is not a valid URL.', $label)); } break; case 'date': $format = Mage::app()->getLocale()->getDateFormat(Varien_Date::DATE_INTERNAL_FORMAT); $validator = new Zend_Validate_Date($format); $validator->setMessage(Mage::helper('customer')->__('"%s" invalid type entered.', $label), Zend_Validate_Date::INVALID); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid date.', $label), Zend_Validate_Date::INVALID_DATE); $validator->setMessage(Mage::helper('customer')->__('"%s" does not fit the entered date format.', $label), Zend_Validate_Date::FALSEFORMAT); break; } } return true; }
/** * Validate value by attribute input validation rule * * @param string $value * @return string */ protected function _validateInputRule($value) { // skip validate empty value if (empty($value)) { return true; } $label = Mage::helper('customer')->__($this->getAttribute()->getStoreLabel()); $validateRules = $this->getAttribute()->getValidateRules(); if (!empty($validateRules['input_validation'])) { switch ($validateRules['input_validation']) { case 'alphanumeric': $validator = new Zend_Validate_Alnum(true); $validator->setMessage(Mage::helper('customer')->__('"%s" invalid type entered.', $label), Zend_Validate_Alnum::INVALID); $validator->setMessage(Mage::helper('customer')->__('"%s" has not only alphabetic and digit characters.', $label), Zend_Validate_Alnum::NOT_ALNUM); $validator->setMessage(Mage::helper('customer')->__('"%s" is an empty string.', $label), Zend_Validate_Alnum::STRING_EMPTY); if (!$validator->isValid($value)) { return $validator->getMessages(); } break; case 'numeric': $validator = new Zend_Validate_Digits(); $validator->setMessage(Mage::helper('customer')->__('"%s" invalid type entered.', $label), Zend_Validate_Digits::INVALID); $validator->setMessage(Mage::helper('customer')->__('"%s" contains not only digit characters.', $label), Zend_Validate_Digits::NOT_DIGITS); $validator->setMessage(Mage::helper('customer')->__('"%s" is an empty string.', $label), Zend_Validate_Digits::STRING_EMPTY); if (!$validator->isValid($value)) { return $validator->getMessages(); } break; case 'alpha': $validator = new Zend_Validate_Alpha(true); $validator->setMessage(Mage::helper('customer')->__('"%s" invalid type entered.', $label), Zend_Validate_Alpha::INVALID); $validator->setMessage(Mage::helper('customer')->__('"%s" has not only alphabetic characters.', $label), Zend_Validate_Alpha::NOT_ALPHA); $validator->setMessage(Mage::helper('customer')->__('"%s" is an empty string.', $label), Zend_Validate_Alpha::STRING_EMPTY); if (!$validator->isValid($value)) { return $validator->getMessages(); } break; case 'email': /** $this->__("'%value%' appears to be a DNS hostname but the given punycode notation cannot be decoded") $this->__("Invalid type given. String expected") $this->__("'%value%' appears to be a DNS hostname but contains a dash in an invalid position") $this->__("'%value%' does not match the expected structure for a DNS hostname") $this->__("'%value%' appears to be a DNS hostname but cannot match against hostname schema for TLD '%tld%'") $this->__("'%value%' does not appear to be a valid local network name") $this->__("'%value%' does not appear to be a valid URI hostname") $this->__("'%value%' appears to be an IP address, but IP addresses are not allowed") $this->__("'%value%' appears to be a local network name but local network names are not allowed") $this->__("'%value%' appears to be a DNS hostname but cannot extract TLD part") $this->__("'%value%' appears to be a DNS hostname but cannot match TLD against known list") */ $validator = new Zend_Validate_EmailAddress(); $validator->setMessage(Mage::helper('customer')->__('"%s" invalid type entered.', $label), Zend_Validate_EmailAddress::INVALID); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid email address.', $label), Zend_Validate_EmailAddress::INVALID_FORMAT); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid hostname.', $label), Zend_Validate_EmailAddress::INVALID_HOSTNAME); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid hostname.', $label), Zend_Validate_EmailAddress::INVALID_MX_RECORD); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid hostname.', $label), Zend_Validate_EmailAddress::INVALID_MX_RECORD); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid email address.', $label), Zend_Validate_EmailAddress::DOT_ATOM); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid email address.', $label), Zend_Validate_EmailAddress::QUOTED_STRING); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid email address.', $label), Zend_Validate_EmailAddress::INVALID_LOCAL_PART); $validator->setMessage(Mage::helper('customer')->__('"%s" exceeds the allowed length.', $label), Zend_Validate_EmailAddress::LENGTH_EXCEEDED); $validator->setMessage(Mage::helper('customer')->__("'%value%' appears to be an IP address, but IP addresses are not allowed"), Zend_Validate_Hostname::IP_ADDRESS_NOT_ALLOWED); $validator->setMessage(Mage::helper('customer')->__("'%value%' appears to be a DNS hostname but cannot match TLD against known list"), Zend_Validate_Hostname::UNKNOWN_TLD); $validator->setMessage(Mage::helper('customer')->__("'%value%' appears to be a DNS hostname but contains a dash in an invalid position"), Zend_Validate_Hostname::INVALID_DASH); $validator->setMessage(Mage::helper('customer')->__("'%value%' appears to be a DNS hostname but cannot match against hostname schema for TLD '%tld%'"), Zend_Validate_Hostname::INVALID_HOSTNAME_SCHEMA); $validator->setMessage(Mage::helper('customer')->__("'%value%' appears to be a DNS hostname but cannot extract TLD part"), Zend_Validate_Hostname::UNDECIPHERABLE_TLD); $validator->setMessage(Mage::helper('customer')->__("'%value%' does not appear to be a valid local network name"), Zend_Validate_Hostname::INVALID_LOCAL_NAME); $validator->setMessage(Mage::helper('customer')->__("'%value%' appears to be a local network name but local network names are not allowed"), Zend_Validate_Hostname::LOCAL_NAME_NOT_ALLOWED); $validator->setMessage(Mage::helper('customer')->__("'%value%' appears to be a DNS hostname but the given punycode notation cannot be decoded"), Zend_Validate_Hostname::CANNOT_DECODE_PUNYCODE); if (!$validator->isValid($value)) { return array_unique($validator->getMessages()); } break; case 'url': $parsedUrl = parse_url($value); if ($parsedUrl === false || empty($parsedUrl['scheme']) || empty($parsedUrl['host'])) { return array(Mage::helper('customer')->__('"%s" is not a valid URL.', $label)); } $validator = new Zend_Validate_Hostname(); if (!$validator->isValid($parsedUrl['host'])) { return array(Mage::helper('customer')->__('"%s" is not a valid URL.', $label)); } break; case 'date': $validator = new Zend_Validate_Date(Varien_Date::DATE_INTERNAL_FORMAT); $validator->setMessage(Mage::helper('customer')->__('"%s" invalid type entered.', $label), Zend_Validate_Date::INVALID); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid date.', $label), Zend_Validate_Date::INVALID_DATE); $validator->setMessage(Mage::helper('customer')->__('"%s" does not fit the entered date format.', $label), Zend_Validate_Date::FALSEFORMAT); if (!$validator->isValid($value)) { return array_unique($validator->getMessages()); } break; } } return true; }
/** * Validate value by attribute input validation rule * * @param string $value * @return array|true * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ protected function _validateInputRule($value) { // skip validate empty value if (empty($value)) { return true; } $label = $this->getAttribute()->getStoreLabel(); $validateRules = $this->getAttribute()->getValidationRules(); $inputValidation = ArrayObjectSearch::getArrayElementByName($validateRules, 'input_validation'); if (!is_null($inputValidation)) { switch ($inputValidation) { case 'alphanumeric': $validator = new \Zend_Validate_Alnum(true); $validator->setMessage(__('"%1" invalid type entered.', $label), \Zend_Validate_Alnum::INVALID); $validator->setMessage(__('"%1" contains non-alphabetic or non-numeric characters.', $label), \Zend_Validate_Alnum::NOT_ALNUM); $validator->setMessage(__('"%1" is an empty string.', $label), \Zend_Validate_Alnum::STRING_EMPTY); if (!$validator->isValid($value)) { return $validator->getMessages(); } break; case 'numeric': $validator = new \Zend_Validate_Digits(); $validator->setMessage(__('"%1" invalid type entered.', $label), \Zend_Validate_Digits::INVALID); $validator->setMessage(__('"%1" contains non-numeric characters.', $label), \Zend_Validate_Digits::NOT_DIGITS); $validator->setMessage(__('"%1" is an empty string.', $label), \Zend_Validate_Digits::STRING_EMPTY); if (!$validator->isValid($value)) { return $validator->getMessages(); } break; case 'alpha': $validator = new \Zend_Validate_Alpha(true); $validator->setMessage(__('"%1" invalid type entered.', $label), \Zend_Validate_Alpha::INVALID); $validator->setMessage(__('"%1" contains non-alphabetic characters.', $label), \Zend_Validate_Alpha::NOT_ALPHA); $validator->setMessage(__('"%1" is an empty string.', $label), \Zend_Validate_Alpha::STRING_EMPTY); if (!$validator->isValid($value)) { return $validator->getMessages(); } break; case 'email': /** __("'%value%' appears to be a DNS hostname but the given punycode notation cannot be decoded") __("Invalid type given. String expected") __("'%value%' appears to be a DNS hostname but contains a dash in an invalid position") __("'%value%' does not match the expected structure for a DNS hostname") __("'%value%' appears to be a DNS hostname but cannot match against hostname schema for TLD '%tld%'") __("'%value%' does not appear to be a valid local network name") __("'%value%' does not appear to be a valid URI hostname") __("'%value%' appears to be an IP address, but IP addresses are not allowed") __("'%value%' appears to be a local network name but local network names are not allowed") __("'%value%' appears to be a DNS hostname but cannot extract TLD part") __("'%value%' appears to be a DNS hostname but cannot match TLD against known list") */ $validator = new \Zend_Validate_EmailAddress(); $validator->setMessage(__('"%1" invalid type entered.', $label), \Zend_Validate_EmailAddress::INVALID); $validator->setMessage(__('"%1" is not a valid email address.', $label), \Zend_Validate_EmailAddress::INVALID_FORMAT); $validator->setMessage(__('"%1" is not a valid hostname.', $label), \Zend_Validate_EmailAddress::INVALID_HOSTNAME); $validator->setMessage(__('"%1" is not a valid hostname.', $label), \Zend_Validate_EmailAddress::INVALID_MX_RECORD); $validator->setMessage(__('"%1" is not a valid hostname.', $label), \Zend_Validate_EmailAddress::INVALID_MX_RECORD); $validator->setMessage(__('"%1" is not a valid email address.', $label), \Zend_Validate_EmailAddress::DOT_ATOM); $validator->setMessage(__('"%1" is not a valid email address.', $label), \Zend_Validate_EmailAddress::QUOTED_STRING); $validator->setMessage(__('"%1" is not a valid email address.', $label), \Zend_Validate_EmailAddress::INVALID_LOCAL_PART); $validator->setMessage(__('"%1" uses too many characters.', $label), \Zend_Validate_EmailAddress::LENGTH_EXCEEDED); $validator->setMessage(__("'%value%' looks like an IP address, which is not an acceptable format."), \Zend_Validate_Hostname::IP_ADDRESS_NOT_ALLOWED); $validator->setMessage(__("'%value%' looks like a DNS hostname but we cannot match the TLD against known list."), \Zend_Validate_Hostname::UNKNOWN_TLD); $validator->setMessage(__("'%value%' looks like a DNS hostname but contains a dash in an invalid position."), \Zend_Validate_Hostname::INVALID_DASH); $validator->setMessage(__("'%value%' looks like a DNS hostname but we cannot match it against the hostname schema for TLD '%tld%'."), \Zend_Validate_Hostname::INVALID_HOSTNAME_SCHEMA); $validator->setMessage(__("'%value%' looks like a DNS hostname but cannot extract TLD part."), \Zend_Validate_Hostname::UNDECIPHERABLE_TLD); $validator->setMessage(__("'%value%' does not look like a valid local network name."), \Zend_Validate_Hostname::INVALID_LOCAL_NAME); $validator->setMessage(__("'%value%' looks like a local network name, which is not an acceptable format."), \Zend_Validate_Hostname::LOCAL_NAME_NOT_ALLOWED); $validator->setMessage(__("'%value%' appears to be a DNS hostname, but the given punycode notation cannot be decoded."), \Zend_Validate_Hostname::CANNOT_DECODE_PUNYCODE); if (!$validator->isValid($value)) { return array_unique($validator->getMessages()); } break; case 'url': $parsedUrl = parse_url($value); if ($parsedUrl === false || empty($parsedUrl['scheme']) || empty($parsedUrl['host'])) { return [__('"%1" is not a valid URL.', $label)]; } $validator = new \Zend_Validate_Hostname(); if (!$validator->isValid($parsedUrl['host'])) { return [__('"%1" is not a valid URL.', $label)]; } break; case 'date': $validator = new \Zend_Validate_Date(\Magento\Framework\Stdlib\DateTime::DATE_INTERNAL_FORMAT); $validator->setMessage(__('"%1" invalid type entered.', $label), \Zend_Validate_Date::INVALID); $validator->setMessage(__('"%1" is not a valid date.', $label), \Zend_Validate_Date::INVALID_DATE); $validator->setMessage(__('"%1" does not fit the entered date format.', $label), \Zend_Validate_Date::FALSEFORMAT); if (!$validator->isValid($value)) { return array_unique($validator->getMessages()); } break; } } return true; }
$private_key = '6LfeneMSAAAAABRYmV5zuUe9AO4i9wppVJAclRlM'; $recaptcha = new Zend_Service_ReCaptcha($public_key, $private_key); if (isset($_POST['send'])) { // validate the user input // if (empty($_POST['recaptcha_response_field'])) { $errors['recaptcha'] = 'reCAPTCHA field is required'; } else { $result = $recaptcha->verify($_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']); if (!$result->isValid()) { $errors['recaptcha'] = 'Try again'; } } // Validate nmae // $val = new Zend_Validate_Alnum(TRUE); if (!$val->isValid($_POST['name'])) { $errors['name'] = 'Name is required'; } // Validate email address // $val = new Zend_Validate_EmailAddress(); if (!$val->isValid($_POST['email'])) { $errors['email'] = 'Email address is required'; } // Validate comments // $val = new Zend_Validate_StringLength(10); if (!$val->isValid($_POST['comments'])) { $errors['comments'] = 'Required'; }
/** * Ensures that getMessages() returns expected default value * * @return void */ public function testGetMessages() { $this->assertEquals(array(), $this->_validator->getMessages()); }
/** * returns an validator for a single category * * @return Zend_Filter_Input validator */ protected function getValidator() { // define filter $filterTrim = new Zend_Filter_StringTrim(); $filterUtf8 = new application_filter_utf8(); $filter = array('id' => $filterTrim, 'name' => array($filterTrim, $filterUtf8), 'position' => $filterTrim); // define validators $validatorId = new application_validate_categoryid(); $validatorId->setMessage(Zend_Registry::get('language')->translate("category doesn't exists"), application_validate_categoryid::NOT_EXISTS); $validatorNotEmpty = new Zend_Validate_NotEmpty(); $validatorNotEmpty->setMessage(Zend_Registry::get('language')->translate("Value is required and can't be empty"), Zend_Validate_NotEmpty::IS_EMPTY); $validatorAlnum = new Zend_Validate_Alnum(true); $validatorAlnum->setMessage(Zend_Registry::get('language')->translate('Only alphanummeric values allowed'), Zend_Validate_Alnum::NOT_ALNUM); $validatorAlnum->setMessage(Zend_Registry::get('language')->translate("Value is required and can't be empty"), Zend_Validate_Alnum::STRING_EMPTY); $validatorNum = new Zend_Validate_Digits(false); $validatorNum->setMessage(Zend_Registry::get('language')->translate('Only digits allowed'), Zend_Validate_Digits::NOT_DIGITS); $validatorNum->setMessage(Zend_Registry::get('language')->translate("Value is required and can't be empty"), Zend_Validate_Digits::STRING_EMPTY); $validators = array('id' => array($validatorId, Zend_Filter_Input::ALLOW_EMPTY => true, Zend_Filter_Input::PRESENCE => Zend_Filter_Input::PRESENCE_OPTIONAL), 'name' => array($validatorNotEmpty, Zend_Filter_Input::ALLOW_EMPTY => false, Zend_Filter_Input::PRESENCE => Zend_Filter_Input::PRESENCE_REQUIRED), 'position' => array($validatorNum, Zend_Filter_Input::PRESENCE => Zend_Filter_Input::PRESENCE_OPTIONAL)); // create validation main object $validator = new Zend_Filter_Input($filter, $validators, array(), array(Zend_Filter_Input::NOT_EMPTY_MESSAGE => Zend_Registry::get('language')->translate("Value is required and can't be empty"), Zend_Filter_Input::BREAK_CHAIN => false)); // return filter input object return $validator; }
/** * The default action is "indexAction", unless explcitly set to something else. */ public function indexAction() { // STAGE 4: Apply business logic to create a presentation model for the view. $origRequest = $this->getInvokeArg('origRequest'); $this->view->rerouteToReason = $this->getInvokeArg('rerouteToReason'); $this->view->origRequestUri = $origRequest->REQUEST_URI; // if no credentials if (empty($_REQUEST['username'])) { // should be _POST, but this makes demo easier to tweak // STAGE 5: Choose view template and submit presentation model to view template for rendering. // if an admin area was requested, and authentication has been enabled in config.ini if (isset($this->authSpace->authenticationId)) { ZFDemo_Log::log(_('already have authentication id, showing logout form')); $this->_forward('logoutDecision'); // show logout form } else { ZFDemo_Log::log(_('no authentication id, showing login form')); $this->renderToSegment('body'); // show login form } return; } // prepare to authenticate credentials received from a form require_once 'Zend/Auth/Result.php'; require_once 'Zend/Auth/Adapter/Digest.php'; $config = Zend_Registry::get('config'); $username = trim($_REQUEST['username']); // ought to be _POST, but this simplifies experimentation $password = trim($_REQUEST['password']); // by the reader of the tutorial // filtering will be added in a later section ///////////////////////////// // ==> SECTION: filter <== require_once 'Zend/Validate/Alnum.php'; require_once 'Zend/Validate/Regex.php'; // input filtering is enabled, so .. $validator_name = new Zend_Validate_Alnum(); // alphabetic and numeric characters are permitted if (!$validator_name->isValid($username)) { $this->renderToSegment('body', 'invalidUsername'); return; } // this application has "special" requirements, so we show how to use custom regex: $validator_password = new Zend_Validate_Regex('/^[a-z0-9_]{5,16}$/'); if (!$validator_password->isValid($password)) { $this->renderToSegment('body', 'invalidPassword'); return; } ///////////////////////////// // ==> SECTION: auth <== $result = false; try { // try to authenticate using the md5 "digest" adapter $filename = $config->authenticate->filename; // file containing username:realm:password digests if ($filename[0] !== DIRECTORY_SEPARATOR) { $filename = Zend_Registry::get('dataDir') . $filename; // prepend path, if filename not absolute } $adapter = new Zend_Auth_Adapter_Digest($filename, $config->authenticate->realm, $username, $password); $result = $adapter->authenticate(); // result of trying to authenticate credentials $this->view->resultCode = $result->getCode(); // allow view to see result status (reason) } catch (Exception $exception) { $this->view->exception = ZFDemo::filterException($exception); // record exception description $this->view->resultCode = false; } if ($result && $result->isValid()) { // if successful authentication, save the authentication identity ( http://framework.zend.com/wiki/x/fUw ) $id = $result->getIdentity(); Zend_Registry::set('authenticationId', $id); // publish the identity (really need Observer pattern) $this->authSpace->authenticationId = $id; $this->authSpace->date = time(); // save the timestamp when authenticated successfully $this->authSpace->attempts = 0; // success, so forget the number of previous login failures // @TODO: filter this ... $this->_redirect($_REQUEST['origPathInfo']); // now return to wherever user came from } else { $this->authSpace->attempts++; // record the authentication failure if ($this->authSpace->attempts > $config->authenticate->maxAttempts) { // Overly simplistic account "lockout" lasts for at least 10 seconds, // but increases with repeated failures. $this->view->lockout = 5 * $this->authSpace->attempts; // Lockout time will be "forgotten" later, and expired from session, allowing logins. $this->authSpace->setExpirationSeconds($this->view->lockout); $this->blockHacker(); // show a view indicating account lockout return; } } // STAGE 5: Choose view template and submit presentation model to view template for rendering. $this->renderToSegment('body'); }
public function registerAction() { //Check to see if user is already login if ($this->loggedEmail) { $this->_redirect('/'); return; } //get referrer $ns = new Zend_Session_Namespace('referrer'); $this->view->referby = $ns->referrer; if ($this->getRequest()->isPost()) { //Validation // Valid email address? if (!Zend_Validate::is($this->_request->getPost('email'), 'EmailAddress') && $this->_request->getPost('email') != 'me2@localhost') { $this->view->errors[] = "Invalid e-mail address."; } //E-mail cannot already exist in the database $user = new Default_Model_User(); $foundUser = $user->getUserByEmail($this->_request->getPost('email')); if (isset($foundUser->id)) { $this->view->errors[] = "Email address already in database."; } //Handle must be between 2-20 characters $validator = new Zend_Validate_StringLength(2, 20); if (!$validator->isValid($this->_request->getPost('handle'))) { $this->view->errors[] = "Handle must be between 2 and 14 characters."; } // Handle must consist solely of alphanumeric characters $validHandle = new Zend_Validate_Alnum(); if (!$validHandle->isValid($this->_request->getPost('handle'))) { $this->view->errors[] = "Handle must consist of letters and numbers."; } // end valid handle // Handle cannot already exist in database $foundUser = $user->getUserByHandle($this->_request->getPost('handle')); if (isset($foundUser->id)) { $this->view->errors[] = "Handle already exists in database."; } // Password must between 6 to 20 characters $validPswd = new Zend_Validate_StringLength(6, 20); if (!$validPswd->isValid($this->_request->getPost('password'))) { $this->view->errors[] = "Password must be at least 6 characters."; } // end valid password // First name must not be empty $validFirstName = new Zend_Validate_NotEmpty(); if (!$validFirstName->isValid($this->_request->getPost('first_name'))) { $this->view->errors[] = "Please provide your first name."; } // end valid first name // Last name must not be empty $validLastName = new Zend_Validate_NotEmpty(); if (!$validLastName->isValid($this->_request->getPost('last_name'))) { $this->view->errors[] = "Please provide your last name."; } // end valid last name // Valid gender? if (!Zend_Validate::is($this->_request->getPost('gender'), 'NotEmpty')) { $this->view->errors[] = "Please identify your gender."; } // end valid gender //Address not empty? if (!Zend_Validate::is($this->_request->getPost('address'), 'NotEmpty')) { $this->view->errors[] = "Please enter your address."; } //if errors exist, prepopulate the form if (count($this->view->errors) > 0) { $this->view->email = $this->_request->getPost('email'); $this->view->handle = $this->_request->getPost('handle'); $this->view->first_name = $this->_request->getPost('first_name'); $this->view->last_name = $this->_request->getPost('last_name'); $this->view->gender = $this->_request->getPost('gender'); $this->view->address = $this->_request->getPost('address'); } else { //No errors, add user to the database and send confirmation e-mail //Generate random keys used for registration confirmation $registrationKey = $this->_helper->generator(32, 'alpha'); // Prepare the data array for database insertion $data = array('email' => $this->_request->getPost('email'), 'password' => md5($this->_request->getPost('password')), 'registration_key' => $registrationKey, 'handle' => $this->_request->getPost('handle'), 'first_name' => $this->_request->getPost('first_name'), 'last_name' => $this->_request->getPost('last_name'), 'gender' => $this->_request->getPost('gender'), 'address' => $this->_request->getPost('address'), 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s'), 'last_login' => date('Y-m-d H:i:s'), 'referby' => $this->_request->getPost('referrer')); //Create a new mail object try { $mail = new Zend_Mail(); // Set the From, To, and Subject headers $mail->setFrom($this->config->email->from_admin); $mail->addTo($this->_request->getPost('email'), "{$this->_request->getPost('first_name')}\n\t\t\t\t\t {$this->_request->getPost('last_name')}"); $mail->setSubject('Your game account has been created'); // Retrieve the e-mail template include "emailTemplates/_email-confirm-registration.phtml"; // Attach the e-mail template to the e-mail and send it $mail->setBodyText($email); $mail->send(); $this->view->success = 1; } catch (Exception $e) { $this->view->errors[] = "We were unable to send your confirmation \t\t\n\t\t\t\t\t\t e-mail.\n\t\t\t\t\tPlease contact {$this->config->email->support}."; } //If succcessful at sending mail, insert into database if ($this->view->success == 1) { // Insert the registration data into the database $user = new Default_Model_User(); $user->insert($data); } } //end else (w/ no errors) } //end if isPost() }
public static function IsValidUsername($username) { $validator = new Zend_Validate_Alnum(); //validates only if the username contain alphebetical and numeric values. return $validator->isValid($username); }
public function __construct($allowWhiteSpace = false) { parent::__construct($allowWhiteSpace); $this->_messageTemplates[self::NOT_ALNUM] = trlKwfStatic("'%value%' has not only alphabetic and digit characters"); $this->_messageTemplates[self::STRING_EMPTY] = trlKwfStatic("'%value%' is an empty string"); }
/** * Функция создание формы * @param type $objForm объект формы * @param type $elementsForm элементы в виде массива * @return type объект формы */ protected function createFormElements($objForm, $elementsForm) { foreach ($elementsForm as $key => $value) { // определяем тип по умолчанию $type = !empty($value['type']) ? $value['type'] : 'text'; // массив с опциями $params = array(); if ($type !== 'hidden') { $params['label'] = !empty($value['label']) ? $value['label'] : die('Не оределлен атрибут label!'); } $params['decorators'] = !empty($value['decorators']) ? $value['decorators'] : $this->elementDecorators(); if (!empty($value['multiOptions'])) { $params['multiOptions'] = $value['multiOptions']; } $value['required'] = !empty($value['required']) ? $value['required'] : true; $value['attribs'] = !empty($value['attribs']) ? $value['attribs'] : array('class' => 'form-control'); $value['filters'] = !empty($value['filters']) ? $value['filters'] : ''; $value['validators'] = !empty($value['validators']) ? $value['validators'] : ''; // присваевыем стандартные фильтры и валидаторы if (empty($value['filters'])) { $stringTrim = new Zend_Filter_StringTrim(); $stripTags = new Zend_Filter_StripTags(); $value['filters'] = array('stringTrim' => $stringTrim, 'stripTags' => $stripTags); } if (empty($value['validators'])) { $alnum = new Zend_Validate_Alnum(); $alnum->setMessage('Только буквы и цыфры!'); $notEmpty = new Zend_Validate_NotEmpty(); $notEmpty->setMessage('Поле обязательно для заполнения', 'isEmpty'); $value['validators'] = array('alnum' => $alnum, 'notEmpty' => $notEmpty); } // провеки на тип если нужен новый то надо добавить по аналогии switch ($type) { case 'text': $elem = new Zend_Form_Element_Text($key); break; case 'textarea': $elem = new Zend_Form_Element_Textarea($key); break; case 'select': $elem = new Zend_Form_Element_Select($key); break; case 'password': $elem = new Zend_Form_Element_Password($key); break; case 'hidden': $elem = new Zend_Form_Element_Hidden($key); break; case 'radio': $elem = new Zend_Form_Element_Radio($key); break; } // присваиваем атрибуты if (!empty($value['attribs'])) { foreach ($value['attribs'] as $k => $val) { $params[$k] = $val; } } // присваиваем опции if (!empty($elem)) { $elem->setOptions($params); } // добавляем валидаторы if (!empty($value['validators']) && $type !== 'hidden') { foreach ($value['validators'] as $val) { $elem->addValidator($val); } } // добавляем фильтры if (!empty($value['filters']) && $type !== 'hidden') { foreach ($value['filters'] as $val) { $elem->addFilter($val); } } // вот тут писец if (!empty($value['required']) && $type !== 'hidden') { $elem->setRequired(TRUE); } // добавляем элемент на форму $objForm->addElement($elem); } // добавляем кнопку $objForm->addElement('submit', 'submit', array('label' => $this->buttonLabel, 'decorators' => $this->buttonDecorators(), 'class' => 'btn btn-default')); return $objForm; }
/** Set the name to query * @access Public * @param string $name * @return string * @throws Pas_Geo_Mapit_Exception */ public function setName($name) { if (is_string($name)) { $validator = new Zend_Validate_Alnum($allowWhiteSpace = true); if (!$validator->isValid($name)) { throw new Pas_Geo_Mapit_Exception('That string is not valid', 500); } else { return $this->_name = $name; } } else { throw new Pas_Geo_Mapit_Exception('The names to search for must be a string', 500); } }
/** * Processes the new password and stores in DB * * @return void */ public function resetpassprocessAction() { if ($this->getRequest()->isPost()) { $password = $this->getRequest()->getPost('password'); $passwordConfirm = $this->getRequest()->getPost('passwordConfirm'); $guid = $this->getRequest()->getPost('guid'); //check valid password $passwordLengthValidator = new Zend_Validate_StringLength(array('min' => MIN_PASS_CHAR, 'max' => MAX_PASS_CHAR)); $alNumValidator = new Zend_Validate_Alnum(); $error = false; if (strcmp($password, $passwordConfirm) != 0) { $this->_helper->flashMessenger->addMessage('Your passwords do not match.'); $error = true; } if (!$passwordLengthValidator->isValid($password)) { if (!$alNumValidator->isValid($password)) { $this->_helper->flashMessenger->addMessage('You password must only consist of letters and numbers.'); $error = true; } else { $this->_helper->flashMessenger->addMessage('Passwords must be between ' . MIN_PASS_CHAR . ' and ' . MAX_CHAR_PASS . ' characters in length.'); $error = true; } } //if validation errors, store data in view if ($error) { $session = new Zend_Session_Namespace(); $session->flashMessengerClass = 'flashMessagesRed'; $session->guid = $guid; $this->_redirect('/login/resetpass/id/' . $guid . '/'); } else { //register use and redirect to success page $options = $this->getInvokeArg('bootstrap')->getOptions(); $salt = $options['password']['salt']; $user = new Model_DbTable_Users(); $passwordReset = new Model_DbTable_PasswordReset(); $id = $passwordReset->getID($guid); $result = $user->changePassword($id, sha1($password . $salt)); $username = $user->getUsername($id); $email = $user->getEmail($id); if ($result != null) { $passwordReset->delete($passwordReset->getAdapter()->quoteInto('guid = ?', $guid)); //send email with username and password. $html = '<p>Your new login information is below:</p>' . '<p>Username: '******'</p>' . '<p>Password: '******'</p>'; $text = "Your new login information is below:\n" . "Username: {$username} . \nPassword: {$password} \n"; $this->sendMail($username, $email, $html, $text, 'Account Information'); $session = new Zend_Session_Namespace(); $session->flashMessengerClass = 'flashMessagesGreen'; $this->_helper->flashMessenger->addMessage('Your password has been successfully reset.'); $this->_redirect('/login/index/'); } else { $session = new Zend_Session_Namespace(); $session->flashMessengerClass = 'flashMessagesRed'; $this->_helper->flashMessenger->addMessage('Your password could not be reset.'); $this->_helper->redirector->gotoRoute(array(), 'forgot-password'); } } } else { $this->_helper->redirector->gotoRoute(array(), 'forgot-password'); } }
public static function IsValidUsername($username) { $validator = new Zend_Validate_Alnum(); return $validator->isValid($username); }
/** * @ZF-7475 */ public function testIntegerValidation() { $this->assertTrue($this->_validator->isValid(1)); }
public function testValidationを実行しエラーの場合はエラーメッセージを取得できる() { $data = array('test1' => '!"#$%&'); $service = Gene::load('Test_ServiceMock'); $service->setAppPath(GENE_TEST_ROOT . '/var'); $valid = $service->getValidator('Test_Service_Validator', 'message.ini'); $result = $valid->isValid($data); $alnum = new Zend_Validate_Alnum(); $template = $alnum->getMessageTemplates(); $messages = $valid->getErrorMessages(); $translate = $service->getSystemTranslate(); $expects = $translate->getAdapter()->getMessages(); $expect = str_replace('%value%', $data['test1'], $expects[$template[Zend_Validate_Alnum::NOT_ALNUM]]); $this->assertSame($expect, $messages[0]); }
public function takenAction() { $username = $this->_getParam('username'); $email = $this->_getParam('email'); // Sent both or neither username/email if ((bool) $username == (bool) $email) { $this->view->status = false; $this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid param count'); return; } // Username must be alnum if ($username) { $validator = new Zend_Validate_Alnum(); if (!$validator->isValid($username)) { $this->view->status = false; $this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid param value'); //$this->view->errors = $validator->getErrors(); return; } $table = Engine_Api::_()->getItemTable('user'); $row = $table->fetchRow($table->select()->where('username = ?', $username)->limit(1)); $this->view->status = true; $this->view->taken = $row !== null; return; } if ($email) { $validator = new Zend_Validate_EmailAddress(); if (!$validator->isValid($email)) { $this->view->status = false; $this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid param value'); //$this->view->errors = $validator->getErrors(); return; } $table = Engine_Api::_()->getItemTable('user'); $row = $table->fetchRow($table->select()->where('email = ?', $email)->limit(1)); $this->view->status = true; $this->view->taken = $row !== null; return; } }
/** * Returns TRUE if every character is alphabetic or a digit, * FALSE otherwise. * * @deprecated since 0.8.0 * @param mixed $value * @return boolean */ public static function isAlnum($value) { require_once 'Zend/Validate/Alnum.php'; $validator = new Zend_Validate_Alnum(); return $validator->isValid($value); }
public function editAction() { $layoutPath = APPLICATION_PATH . '/templates/' . TEMPLATE_USED; $option = array('layout' => 'hethong/layout', 'layoutPath' => $layoutPath); Zend_Layout::startMvc($option); $translate = Zend_Registry::get('Zend_Translate'); $this->view->title = 'Quản lý tài khoản - ' . $translate->_('TEXT_DEFAULT_TITLE'); $this->view->headTitle($this->view->title); $id = $this->_getParam('id', 0); $userModel = new Front_Model_Users(); $employeesModel = new Front_Model_Employees(); $groupsModel = new Front_Model_Groups(); $list_employees = $employeesModel->fetchAll(); $list_groups = $groupsModel->fetchAll(); $error_message = array(); $success_message = ''; $user_info = $userModel->fetchRow('user_id=' . $id); if (!$user_info) { $error_message[] = 'Không tìm thấy thông tin của tài khoản.'; } if ($this->_request->isPost()) { $username = trim($this->_arrParam['username']); $password = trim($this->_arrParam['password']); $employee = $this->_arrParam['employee']; $group = $this->_arrParam['group']; $status = $this->_arrParam['status']; $validator_length = new Zend_Validate_StringLength(array('min' => 4, 'max' => 12)); $validator_username = new Zend_Validate_Alnum(array('allowWhiteSpace' => false)); //kiem tra dữ liệu if (!$validator_length->isValid($username)) { $error_message[] = 'Tên tài khoản phải bằng hoặc hơn 4 ký tự và nhỏ hơn hoặc bằng 12 ký tự.'; } if (!$validator_username->isValid($username)) { $error_message[] = 'Tên tài khoản không không được chứa khoảng trắng.'; } if ($password) { if (!$validator_length->isValid($password)) { $error_message[] = 'Mật khẩu phải bằng hoặc hơn 4 ký tự và nhỏ hơn hoặc bằng 12 ký tự.'; } } //check username đã tồn tại $check_username = $userModel->fetchRow('username="******" and username !="' . $user_info->username . '"'); if ($check_username) { $error_message[] = 'Tên đăng nhập <strong>' . $username . '</strong> đã tồn tại.'; } //check employee $check_employee = $userModel->fetchRow('em_id=' . $employee . ' and em_id !=' . $user_info->em_id); if ($check_employee) { $error_message[] = 'Nhân viên <strong>' . $this->view->viewGetName($employee) . '</strong> đã có tài khoản rồi.'; } if (!sizeof($error_message)) { $current_time = new Zend_Db_Expr('NOW()'); $userModel->update(array('em_id' => $employee, 'group_id' => $group, 'username' => $username, 'status' => $status, 'date_modified' => $current_time), 'user_id=' . $id); if ($password) { $userModel->update(array('password' => md5($password)), 'user_id=' . $id); } $user_info->em_id = $employee; $user_info->group_id = $group; $user_info->username = $username; $user_info->status = $status; $success_message = 'Đã cập nhật thông tin tài khoản thành công.'; } } $this->view->user_info = $user_info; $this->view->success_message = $success_message; $this->view->error_message = $error_message; $this->view->list_groups = $list_groups; $this->view->list_employees = $list_employees; }
protected function _createAlnumValidator($errorMessage) { $alnumValidator = new Zend_Validate_Alnum(); $alnumValidator->setMessage($errorMessage, Zend_Validate_Alnum::NOT_ALNUM); return $alnumValidator; }
/** * Defined by Zend_Validate_Interface * * Returns true if and only if $value contains only alphabetic and digit characters * * @param string $value * @return boolean */ public function isValid($value) { if (!is_string($value) && !is_int($value) && !is_float($value)) { $this->_error(self::INVALID); return false; } $this->_setValue($value); if ('' === $value) { $this->_error(self::STRING_EMPTY); return false; } if (null === self::$_filter) { /** * @see Zend_Filter_Alnum */ //require_once 'Zend/Filter/Alnum.php'; self::$_filter = new Zend_Filter_Alnum(); } self::$_filter->allowWhiteSpace = $this->allowWhiteSpace; if ($value != self::$_filter->filter($value)) { $this->_error(self::NOT_ALNUM); return false; } return true; }
function regAction() { if ($this->_request->isPost('reg-form')) { Zend_Loader::loadClass('Zend_Filter_StripTags'); Zend_Loader::loadClass('Zend_File_Transfer'); Zend_Loader::loadClass('Zend_Date'); Zend_Loader::loadClass('Zend_Mail'); Zend_Loader::loadClass('Zend_Validate_EmailAddress'); Zend_Loader::loadClass('Zend_Validate_StringLength'); Zend_Loader::loadClass('Zend_Validate_Alnum'); $filter = new Zend_Filter_StripTags(); $email = trim($filter->filter($this->_request->getPost('reg-email'))); $username = trim($filter->filter($this->_request->getPost('reg-name'))); $password = trim($filter->filter($this->_request->getPost('reg-pswd'))); $password_confirm = trim($filter->filter($this->_request->getPost('reg-pswd-verification'))); $real_name = trim($filter->filter($this->_request->getPost('reg-real-name'))); $file_name = ''; $warnings = new Zend_Session_Namespace(); $warnings->username = $username; $warnings->email = $email; $warnings->real_name = $real_name; $warnings->error = ''; $error_msg = ''; $mail_val = new Zend_Validate_EmailAddress(); $name_lenght_val = new Zend_Validate_StringLength(6, 12); $name_an_val = new Zend_Validate_Alnum(); $pass_lenght_val = new Zend_Validate_StringLength(6, 16); $real_name_lenght_val = new Zend_Validate_StringLength(0, 60); if ($email == '') { $error_msg .= '<p>Enter your email.</p>'; } else { if (!$mail_val->isValid($email)) { foreach ($mail_val->getMessages() as $message) { $error_msg .= '<p>' . $message . '</p>'; } } else { $data = new Users(); $query = 'email = "' . $email . '"'; $data_row = $data->fetchRow($query); if ($data_row['email'] != '') { $error_msg .= '<p>User with such an email is already registered.</p>'; } } } if ($username == '') { $error_msg .= '<p>Enter your username.</p>'; } else { if (!$name_lenght_val->isValid($username) || !$name_an_val->isValid($username)) { foreach ($name_lenght_val->getMessages() as $message) { $error_msg .= '<p>' . $message . '</p>'; } foreach ($name_an_val->getMessages() as $message) { $error_msg .= '<p>' . $message . '</p>'; } } else { $data = new Users(); $query = 'login = "******"'; $data_row = $data->fetchRow($query); if ($data_row['login'] != '') { $error_msg .= '<p>User with such an username is already registered.</p>'; } } } if ($password == '' || !$pass_lenght_val->isValid($password)) { $error_msg .= '<p>Enter password (must consist 6 to 16 characters).</p>'; } else { if ($password_confirm == '') { $error_msg .= '<p>Empty verification password.</p>'; } else { if ($password != $password_confirm) { $error_msg .= '<p>The entered passwords do not match.</p>'; } else { $salt = substr(sha1(microtime(true) . rand(1, 99999)), 0, 3); $password = sha1($password . $salt); } } } if ($real_name != '') { if (!$real_name_lenght_val->isValid($real_name)) { foreach ($real_name_lenght_val->getMessages() as $message) { $error_msg .= '<p>' . $message . '</p>'; } } } $upload = new Zend_File_Transfer(); if ($upload->isUploaded()) { $upload->setDestination('public/upload/avatars/'); $upload->addValidator('IsImage', false); $upload->addValidator('Size', false, 1024 * 1024); if (!$upload->isValid()) { foreach ($upload->getMessages() as $message) { $error_msg .= '<p>' . $message . '</p>'; } } else { $upload_info = $upload->getFileName(); $file_ext = mb_substr($upload_info, strrpos($upload_info, '.') + 1); $file_name = $username . '.' . $file_ext; $upload->addFilter('Rename', array('target' => 'public/upload/avatars/' . $file_name, 'overwrite' => true)); } } if ($error_msg != '') { $warnings->error = $error_msg; $warnings->status = ''; $this->_redirect('/register/'); return; } else { $date = new Zend_Date(); $current_date = $date->toString('YYYY-MM-dd'); $upload->receive(); $data = array('login' => $username, 'email' => $email, 'password' => $password, 'salt' => $salt, 'real_name' => $real_name, 'reg_date' => $current_date, 'avatar' => $file_name, 'last_login' => '-'); $user = new Users(); $user->insert($data); $warnings->error = '<p>Registration complete.</p><p>Now check your E-Mail to activate your profile.</p>'; $warnings->username = ''; $warnings->email = ''; $warnings->real_name = ''; $warnings->status = ' reg_ok'; $mail = new Zend_Mail(); $hash = sha1($email . $salt); $url = $this->getRequest()->getServer('HTTP_HOST'); $mail->setBodyHtml('<p>To activate your profile follow the link below:</p> <p>Link: <a href="http://' . $url . '/register/activate/' . $hash . '">http://' . $url . '/register/activate/' . $hash . '</a></p> <p>Thanks for your registration.</p> '); $mail->setFrom('*****@*****.**', 'Administrator'); $mail->addTo($email, $username); $mail->setSubject('Test activation link'); $mail->send(); $this->_redirect('/register/'); return; } } }