/** * This function first gets values from mapped fields and then check these values against * Mollom web service and then notify callback object with the spam checking result. * @param Validator $validator * @return boolean - true when Mollom confirms that the submission is ham (not spam) * - false when Mollom confirms that the submission is spam * - false when Mollom say 'unsure'. * In this case, 'mollom_captcha_requested' session is set to true * so that Field() knows it's time to display captcha */ public function validate($validator) { // Check that, if necessary, the user has given permission to check for spam $requireConfirmation = Config::inst()->get('AkismetSpamProtector', 'require_confirmation'); if ($requireConfirmation && !$this->Value()) { $validator->validationError($this->name, _t('AkismetField.NOTIFICATIONREQUIRED', 'You must give consent to submit this content to spam detection'), "error"); return false; } // Check result $isSpam = $this->getIsSpam(); if (!$isSpam) { return true; } // Save error message $errorMessage = _t('AkismetField.SPAM', "Your submission has been rejected because it was treated as spam."); // If spam should be allowed, let it pass and save it for later if (Config::inst()->get('AkismetSpamProtector', 'save_spam')) { // In order to save spam but still display the spam message, we must mock a form message // without failing the validation $errors = array(array('fieldName' => $this->name, 'message' => $errorMessage, 'messageType' => 'error')); $formName = $this->getForm()->FormName(); Session::set("FormInfo.{$formName}.errors", $errors); return true; } else { // Mark as spam $validator->validationError($this->name, $errorMessage, "error"); return false; } }
/** * Validate this field as a valid hostname * * @param Validator $validator * @return bool */ public function validate($validator) { if ($this->checkHostname($this->Value())) { return true; } $validator->validationError($this->getName(), _t("DomainNameField.INVALID_DOMAIN", "Invalid domain name"), "validation"); return false; }
/** * Validate this field * * @param Validator $validator * @return bool */ public function validate($validator) { if (!is_null($this->maxLength) && mb_strlen($this->value) > $this->maxLength) { $validator->validationError($this->name, _t('TextField.VALIDATEMAXLENGTH', 'The value for {name} must not exceed {maxLength} characters in length', array('name' => $this->getName(), 'maxLength' => $this->maxLength)), "validation"); return false; } return true; }
/** * Validate this field * * @param Validator $validator * @return bool */ public function validate($validator) { if (!$this->value) { return true; } if ($this->isNumeric()) { return true; } $validator->validationError($this->name, _t('NumericField.VALIDATION', "'{value}' is not a number, only numbers can be accepted for this field", array('value' => $this->value)), "validation"); return false; }
/** * Validate this field * * @param Validator $validator * @return bool */ public function validate($validator) { if (self::getValidateOnSubmit()) { return true; } else { if (strtoupper($this->value) === SimpleCaptchaController::getCaptchaID()) { return true; } $validator->validationError($this->name, sprintf("%s is wrong, Correct captcha is required", $this->value), "validation"); return false; } }
/** * Validates for RFC 2822 compliant email addresses. * * @see http://www.regular-expressions.info/email.html * @see http://www.ietf.org/rfc/rfc2822.txt * * @param Validator $validator * * @return string */ public function validate($validator) { $this->value = trim($this->value); $pattern = '^[a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$'; // Escape delimiter characters. $safePattern = str_replace('/', '\\/', $pattern); if ($this->value && !preg_match('/' . $safePattern . '/i', $this->value)) { $validator->validationError($this->name, _t('EmailField.VALIDATION', 'Please enter an email address'), 'validation'); return false; } return true; }
/** * Checks if a certain field value is valid. * * @param string $value * @param Validator $validator */ public function validateValue($value, $validator) { if (!$this->Required) { return; } if (is_array($value)) { return; } // eg. checkbox set values if (!strlen($value)) { $validator->validationError('MetadataRaw', sprintf('The metadata field "%s" on the "%s" schema is required', $this->Title, $this->Schema()->Title), 'validation'); } }
/** * Validates for RFC 2822 compliant email adresses. * * @see http://www.regular-expressions.info/email.html * @see http://www.ietf.org/rfc/rfc2822.txt * * @param Validator $validator * @return String */ function validate($validator) { $this->value = trim($this->value); $pcrePattern = '^[a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$'; // PHP uses forward slash (/) to delimit start/end of pattern, so it must be escaped $pregSafePattern = str_replace('/', '\\/', $pcrePattern); if ($this->value && !preg_match('/' . $pregSafePattern . '/i', $this->value)) { $validator->validationError($this->name, _t('EmailField.VALIDATION', "Please enter an email address."), "validation"); return false; } else { return true; } }
/** * Validate this field * * @param Validator $validator * @return bool */ public function validate($validator) { $value = isset($_POST[$this->name . '_custom']) ? $_POST[$this->name . '_custom'] : null; if (!$value) { return true; } // no custom value, don't validate // Check that the current date with the date format is valid or not require_once 'Zend/Date.php'; $date = Zend_Date::now()->toString($value); $valid = Zend_Date::isDate($date, $value); if ($valid) { return true; } else { if ($validator) { $validator->validationError($this->name, _t('MemberDatetimeOptionsetField.DATEFORMATBAD', "Date format is invalid"), "validation", false); } return false; } }
/** * Validate this field * * @param Validator $validator * @return bool */ public function validate($validator) { $name = $this->name; // if field isn't visible, don't validate if (!$this->isSaveable()) { return true; } $this->passwordField->setValue($this->value); $this->confirmPasswordfield->setValue($this->confirmValue); $value = $this->passwordField->Value(); // both password-fields should be the same if ($value != $this->confirmPasswordfield->Value()) { $validator->validationError($name, _t('Form.VALIDATIONPASSWORDSDONTMATCH', "Passwords don't match"), "validation"); return false; } if (!$this->canBeEmpty) { // both password-fields shouldn't be empty if (!$value || !$this->confirmPasswordfield->Value()) { $validator->validationError($name, _t('Form.VALIDATIONPASSWORDSNOTEMPTY', "Passwords can't be empty"), "validation"); return false; } } // lengths if ($this->minLength || $this->maxLength) { $errorMsg = null; $limit = null; if ($this->minLength && $this->maxLength) { $limit = "{{$this->minLength},{$this->maxLength}}"; $errorMsg = _t('ConfirmedPasswordField.BETWEEN', 'Passwords must be {min} to {max} characters long.', array('min' => $this->minLength, 'max' => $this->maxLength)); } elseif ($this->minLength) { $limit = "{{$this->minLength}}.*"; $errorMsg = _t('ConfirmedPasswordField.ATLEAST', 'Passwords must be at least {min} characters long.', array('min' => $this->minLength)); } elseif ($this->maxLength) { $limit = "{0,{$this->maxLength}}"; $errorMsg = _t('ConfirmedPasswordField.MAXIMUM', 'Passwords must be at most {max} characters long.', array('max' => $this->maxLength)); } $limitRegex = '/^.' . $limit . '$/'; if (!empty($value) && !preg_match($limitRegex, $value)) { $validator->validationError($name, $errorMsg, "validation"); } } if ($this->requireStrongPassword) { if (!preg_match('/^(([a-zA-Z]+\\d+)|(\\d+[a-zA-Z]+))[a-zA-Z0-9]*$/', $value)) { $validator->validationError($name, _t('Form.VALIDATIONSTRONGPASSWORD', "Passwords must have at least one digit and one alphanumeric character"), "validation"); return false; } } // Check if current password is valid if (!empty($value) && $this->getRequireExistingPassword()) { if (!$this->currentPasswordValue) { $validator->validationError($name, _t('ConfirmedPasswordField.CURRENT_PASSWORD_MISSING', "You must enter your current password."), "validation"); return false; } // Check this password is valid for the current user $member = Member::currentUser(); if (!$member) { $validator->validationError($name, _t('ConfirmedPasswordField.LOGGED_IN_ERROR', "You must be logged in to change your password."), "validation"); return false; } // With a valid user and password, check the password is correct $checkResult = $member->checkPassword($this->currentPasswordValue); if (!$checkResult->valid()) { $validator->validationError($name, _t('ConfirmedPasswordField.CURRENT_PASSWORD_ERROR', "The current password you have entered is not correct."), "validation"); return false; } } return true; }
/** * @param string $fieldName * @param string $message * @param string $messageType */ public function validationError($fieldName, $message, $messageType = '') { // Just make any error use the form message $this->form->sessionMessage($message, $messageType); parent::validationError($fieldName, $message, $messageType); }
/** * Validate the value of this EmailField agianst our list of allowed and disallowed domains * @param Validator $validator * @return bool */ protected function validateDomain(Validator $validator) { // If we can't get a domain from the current value, just quite validating the domain. $domain = $this->getDomain(); if (!$domain) { return true; } // Validate against the allowed domain list if ($this->allowedDomains && !$this->valueInList($domain, $this->allowedDomains)) { // Build the message $message = _t('DomainSpecificEmailField.ALLOWEDDOMAIN', 'The email address is not from an allowed domain.'); if ($this->showListOnError) { $message .= ' ' . _t('DomainSpecificEmailField.ALLOWEDDOMAINLLIST', 'The following domains are allowed: ') . implode(', ', $this->allowedDomains); } // Record the error $validator->validationError($this->getName(), $message); return false; } // Validate against the disallowed domain list if ($this->disallowedDomains && $this->valueInList($domain, $this->disallowedDomains)) { // Build messgae $message = _t('DomainSpecificEmailField.DISALLOWEDDOMAIN', 'The email address is from a disallowed domain.'); if ($this->showListOnError) { $message .= ' ' . _t('DomainSpecificEmailField.DISALLOWEDDOMAINLLIST', 'The following domains are disallowed: ') . implode(', ', $this->disallowedDomains); } // Record error $validator->validationError($this->getName(), $message); return false; } // Made it all the way without incident. Domain is valid. return true; }
/** * Validate this field * * @param Validator $validator * @return bool */ public function validate($validator) { $valid = false; $source = $this->getSourceAsArray(); $disabled = $this->getDisabledItems(); if ($this->value) { foreach ($source as $value => $title) { if (is_array($title) && array_key_exists($this->value, $title)) { // Check that the set value is not in the list of disabled items if (!isset($disabled[$value]) || !in_array($this->value, $disabled[$value])) { $valid = true; } // Check that the value matches and is not disabled } elseif ($this->value == $value && !in_array($this->value, $disabled)) { $valid = true; } } } elseif ($this->getHasEmptyDefault()) { $valid = true; } if (!$valid) { $validator->validationError($this->name, _t('DropdownField.SOURCE_VALIDATION', "Please select a value within the list provided. {value} is not a valid option", array('value' => $this->value)), "validation"); return false; } return true; }
/** * Validate the captcha information * * @param Validator $validator * * @return boolean */ public function validate($validator) { // Bypass spam detection for eligible users if ($this->exemptUser()) { $this->clearMollomSession(); return true; } $session_id = Session::get("mollom_session_id"); $mapped = $this->getSpamMappedData(); $data = array(); // prepare submission foreach (array('authorName', 'authorUrl', 'authorMail', 'authorIp', 'authorId') as $k) { if (isset($mapped[$k])) { $data[$k] = $mapped[$k]; } } if ($session_id) { // session ID exists so has been checked by captcha $data['id'] = $session_id; $data['solution'] = $this->Value(); $result = $this->getMollom()->checkCaptcha($data); if (is_array($result)) { if ($result['solved']) { $this->clearMollomSession(); return true; } else { $this->requestMollom(); $validator->validationError($this->name, _t('MollomCaptchaField.CAPTCHAREQUESTED', "Please answer the captcha question", "Mollom Captcha provides words in an image, and expects a user to type them in a textfield"), "warning"); return false; } } } else { $contentMap = array('id' => 'id', 'title' => 'postTitle', 'body' => 'postBody'); foreach ($contentMap as $k => $v) { if (isset($mapped[$k])) { $data[$v] = $mapped[$k]; } } $result = $this->getMollom()->checkContent($data); // Mollom can do much more useful things. // @todo handle profanityScore, qualityScore, sentimentScore, reason if (is_array($result)) { switch ($result['spamClassification']) { case 'ham': $this->clearMollomSession(); return true; case 'unsure': $this->requestMollom(); // we're unsure so request the captcha. $validator->validationError($this->name, _t('MollomCaptchaField.CAPTCHAREQUESTED', "Please answer the captcha question", "Mollom Captcha provides words in an image, and expects a user to type them in a textfield"), "warning"); return false; case 'spam': $this->clearMollomSession(); $this->requestMollom(); $validator->validationError($this->name, _t('MollomCaptchaField.SPAM', "Your submission has been rejected because it was treated as spam.", "Mollom Captcha provides words in an image, and expects a user to type them in a textfield"), "error"); return false; break; } } } return true; }
/** * Validate by submitting to external service * * @todo implement socket timeout handling (or switch to curl?) * @param Validator $validator * @return boolean */ public function validate($validator) { // don't bother querying the recaptcha-service if fields were empty if (!isset($_REQUEST['g-recaptcha-response']) || empty($_REQUEST['g-recaptcha-response'])) { $validator->validationError($this->name, _t('RecaptchaField.EMPTY', "Please answer the captcha question", "Recaptcha (https://www.google.com/recaptcha) protects this website " . "from spam and abuse."), "validation", false); return false; } $response = $this->recaptchaHTTPPost($_REQUEST['g-recaptcha-response']); if (!$response) { $validator->validationError($this->name, _t('RecaptchaField.NORESPONSE', "The recaptcha service gave no response. Please try again later.", "Recaptcha (https://www.google.com/recaptcha) protects this website " . "from spam and abuse."), "validation", false); return false; } // get the payload of the response and decode it $response = json_decode($response, true); if ($response['success'] != 'true') { // Count some errors as "user level", meaning they raise a validation error rather than a system error $userLevelErrors = array('missing-input-response', 'invalid-input-response'); if (count(array_intersect($response['error-codes'], $userLevelErrors)) === 0) { $error = implode(', ', $response['error-codes']); user_error("RecatpchaField::validate(): Recaptcha-service error: '{$error}'", E_USER_ERROR); return false; } else { // Internal error-string returned by recaptcha, e.g. "incorrect-captcha-sol". // Used to generate the new iframe-url/js-url after form-refresh. Session::set("FormField.{$this->form->FormName()}.{$this->getName()}.error", trim($error)); $validator->validationError($this->name, _t('RecaptchaField.VALIDSOLUTION', "Your answer didn't match the captcha words, please try again", "Recaptcha (https://www.google.com/recaptcha) protects this website " . "from spam and abuse."), "validation", false); return false; } } return true; }
/** * Validate this field * * @param Validator $validator * @return bool */ public function validate($validator) { // Check if valid value is given $selected = $this->Value(); if (strlen($selected)) { // Use selection rules to check which are valid foreach ($this->getValidValues() as $formValue) { if ($this->isSelectedValue($formValue, $selected)) { return true; } } } else { if ($this->getHasEmptyDefault()) { // Check empty value return true; } $selected = '(none)'; } // Fail $validator->validationError($this->name, _t('DropdownField.SOURCE_VALIDATION', "Please select a value within the list provided. {value} is not a valid option", array('value' => $selected)), "validation"); return false; }
/** * @param Validator $validator * * @return boolean */ public function validate($validator) { $name = $this->name; // if field isn't visible, don't validate if (!$this->isSaveable()) { return true; } $passwordField = $this->children->fieldByName($name . '[_Password]'); $passwordConfirmField = $this->children->fieldByName($name . '[_ConfirmPassword]'); $passwordField->setValue($_POST[$name]['_Password']); $passwordConfirmField->setValue($_POST[$name]['_ConfirmPassword']); $value = $passwordField->Value(); // both password-fields should be the same if ($value != $passwordConfirmField->Value()) { $validator->validationError($name, _t('Form.VALIDATIONPASSWORDSDONTMATCH', "Passwords don't match"), "validation", false); return false; } if (!$this->canBeEmpty) { // both password-fields shouldn't be empty if (!$value || !$passwordConfirmField->Value()) { $validator->validationError($name, _t('Form.VALIDATIONPASSWORDSNOTEMPTY', "Passwords can't be empty"), "validation", false); return false; } } // lengths if ($this->minLength || $this->maxLength) { if ($this->minLength && $this->maxLength) { $limit = "{{$this->minLength},{$this->maxLength}}"; $errorMsg = _t('ConfirmedPasswordField.BETWEEN', 'Passwords must be {min} to {max} characters long.', array('min' => $this->minLength, 'max' => $this->maxLength)); } elseif ($this->minLength) { $limit = "{{$this->minLength}}.*"; $errorMsg = _t('ConfirmedPasswordField.ATLEAST', 'Passwords must be at least {min} characters long.', array('min' => $this->minLength)); } elseif ($this->maxLength) { $limit = "{0,{$this->maxLength}}"; $errorMsg = _t('ConfirmedPasswordField.MAXIMUM', 'Passwords must be at most {max} characters long.', array('max' => $this->maxLength)); } $limitRegex = '/^.' . $limit . '$/'; if (!empty($value) && !preg_match($limitRegex, $value)) { $validator->validationError($name, $errorMsg, "validation", false); } } if ($this->requireStrongPassword) { if (!preg_match('/^(([a-zA-Z]+\\d+)|(\\d+[a-zA-Z]+))[a-zA-Z0-9]*$/', $value)) { $validator->validationError($name, _t('Form.VALIDATIONSTRONGPASSWORD', "Passwords must have at least one digit and one alphanumeric character"), "validation", false); return false; } } return true; }
/** * Validate this field * * @param Validator $validator * @return bool */ public function validate($validator) { $values = $this->value; if (!$values) { return true; } $sourceArray = $this->getSourceAsArray(); if (is_array($values)) { if (!array_intersect_key($sourceArray, $values)) { $validator->validationError($this->name, _t('CheckboxSetField.SOURCE_VALIDATION', "Please select a value within the list provided. '{value}' is not a valid option", array('value' => implode(' and ', array_diff($sourceArray, $values)))), "validation"); return false; } } else { if (!in_array($this->value, $sourceArray)) { $validator->validationError($this->name, _t('CheckboxSetField.SOURCE_VALIDATION', "Please select a value within the list provided. '{value}' is not a valid option", array('value' => $this->value)), "validation"); return false; } } return true; }
/** * Validate this field * * @param Validator $validator * @return bool */ public function validate($validator) { $source = $this->getSourceAsArray(); $disabled = $this->getDisabledItems(); if (!array_key_exists($this->value, $source) || in_array($this->value, $disabled)) { if ($this->getHasEmptyDefault() && !$this->value) { return true; } $validator->validationError($this->name, _t('DropdownField.SOURCE_VALIDATION', "Please select a value within the list provided. {value} is not a valid option", array('value' => $this->value)), "validation"); return false; } return true; }
/** * Validation method for this field, called when the entire form is validated * * @param Validator $validator * @return boolean */ public function validate($validator) { $name = $this->getName(); $value = $this->Value(); // If there is no file then quit if (!$value) { return true; } // Revalidate each file against nested validator $this->getUpload()->clearErrors(); // Generate $_FILES style file attribute array for upload validator $store = $this->getAssetStore(); $mime = $store->getMimeType($value['Filename'], $value['Hash'], $value['Variant']); $metadata = $store->getMetadata($value['Filename'], $value['Hash'], $value['Variant']); $tmpFile = array('name' => $value['Filename'], 'type' => $mime, 'size' => isset($metadata['size']) ? $metadata['size'] : 0, 'tmp_name' => null, 'error' => UPLOAD_ERR_OK); $this->getUpload()->validate($tmpFile); // Check all errors if ($errors = $this->getUpload()->getErrors()) { foreach ($errors as $error) { $validator->validationError($name, $error, "validation"); } return false; } return true; }
/** * Validate this field * * @param Validator $validator * @return bool */ public function validate($validator) { $values = $this->value; if (!$values) { return true; } $source = $this->getSourceAsArray(); if (is_array($values)) { if (!array_intersect_key($source, array_flip($values))) { $validator->validationError($this->name, _t("Please select a value within the list provided. {value} is not a valid option", array('value' => $this->value)), "validation"); return false; } } else { if (!array_key_exists($this->value, $source)) { $validator->validationError($this->name, _t('ListboxField.SOURCE_VALIDATION', "Please select a value within the list provided. %s is not a valid option", array('value' => $this->value)), "validation"); return false; } } return true; }
/** * Validate by submitting to external service * * @todo implement socket timeout handling (or switch to curl?) * @param Validator $validator * @return boolean */ public function validate($validator) { // don't bother querying the recaptcha-service if fields were empty if (!isset($_REQUEST['recaptcha_challenge_field']) || empty($_REQUEST['recaptcha_challenge_field']) || !isset($_REQUEST['recaptcha_response_field']) || empty($_REQUEST['recaptcha_response_field'])) { $validator->validationError($this->name, _t('RecaptchaField.EMPTY', "Please answer the captcha question", PR_MEDIUM, "Recaptcha (http://recaptcha.net) provides two words in an image, and expects a user to type them in a textfield"), "validation", false); return false; } $response = $this->recaptchaHTTPPost($_REQUEST['recaptcha_challenge_field'], $_REQUEST['recaptcha_response_field']); if (!$response) { $validator->validationError($this->name, _t('RecaptchaField.NORESPONSE', "The recaptcha service gave no response. Please try again later.", PR_MEDIUM, "Recaptcha (http://recaptcha.net) provides two words in an image, and expects a user to type them in a textfield"), "validation", false); return false; } // get the payload of the response and split it by newlines list($isValid, $error) = explode("\n", $response, 2); if ($isValid != 'true') { // Count some errors as "user level", meaning they raise a validation error rather than a system error $userLevelErrors = array('incorrect-captcha-sol', 'invalid-request-cookie'); if (!in_array(trim($error), $userLevelErrors)) { user_error("RecatpchaField::validate(): Recaptcha-service error: '{$error}'", E_USER_ERROR); return false; } else { // Internal error-string returned by recaptcha, e.g. "incorrect-captcha-sol". // Used to generate the new iframe-url/js-url after form-refresh. Session::set("FormField.{$this->form->FormName()}.{$this->Name()}.error", trim($error)); $validator->validationError($this->name, _t('RecaptchaField.VALIDSOLUTION', "Your answer didn't match the captcha words, please try again", PR_MEDIUM, "Recaptcha (http://recaptcha.net) provides two words in an image, and expects a user to type them in a textfield"), "validation", false); return false; } } return true; }
/** * Validation method for this field, called when the entire form is validated * * @param Validator $validator * @return boolean */ public function validate($validator) { // @todo Test compatibility with RequiredFields $name = $this->getName(); $files = $this->getItems(); // If there are no files then quit if ($files->count() == 0) { return true; } // Check max number of files $maxFiles = $this->getAllowedMaxFileNumber(); if ($maxFiles && $files->count() > $maxFiles) { $validator->validationError($name, _t('UploadField.MAXNUMBEROFFILES', 'Max number of {count} file(s) exceeded.', array('count' => $maxFiles)), "validation"); return false; } // Revalidate each file against nested validator $this->upload->clearErrors(); foreach ($files as $file) { // Generate $_FILES style file attribute array for upload validator $tmpFile = array('name' => $file->Name, 'type' => null, 'size' => $file->AbsoluteSize, 'tmp_name' => null, 'error' => UPLOAD_ERR_OK); $this->upload->validate($tmpFile); } // Check all errors if ($errors = $this->upload->getErrors()) { foreach ($errors as $error) { $validator->validationError($name, $error, "validation"); } return false; } return true; }
/** * Validate this field * * @todo Very basic validation at the moment * * @param Validator $validator * @return bool */ public function validate($validator) { $valid = preg_match('/^[0-9\\+\\-\\(\\)\\s\\#]*$/', $this->joinPhoneNumber($this->value)); if (!$valid) { $validator->validationError($this->name, _t('PhoneNumberField.VALIDATION', "Please enter a valid phone number"), "validation", false); return false; } return true; }
/** * Validate this field * * @param Validator $validator * @return bool */ public function validate($validator) { $value = $this->Value(); if (!$value) { return true; // no custom value, don't validate } // Check that the current date with the date format is valid or not require_once 'Zend/Date.php'; $date = Zend_Date::now()->toString($value); $valid = Zend_Date::isDate($date, $value); if ($valid) { return true; } // Fail $validator->validationError($this->getName(), _t('MemberDatetimeOptionsetField.DATEFORMATBAD', "Date format is invalid"), "validation"); return false; }
/** * Validate this field * * @param Validator $validator * @return bool */ public function validate($validator) { // Don't validate empty fields if (empty($this->value)) { return true; } if (!Zend_Date::isDate($this->value, $this->getConfig('timeformat'), $this->locale)) { $validator->validationError($this->name, _t('TimeField.VALIDATEFORMAT', "Please enter a valid time format ({format})", array('format' => $this->getConfig('timeformat'))), "validation", false); return false; } return true; }
/** * Please note that we do NOT validate an empty field. Add a required * constraint if you want a value * * @param Validator $validator * @return boolean */ public function validate($validator) { if (empty($this->value)) { return true; } try { $valid = self::validatePhoneNumber($this->value, $this->getTargetCountryCode()); } catch (\libphonenumber\NumberParseException $e) { $valid = false; //if it wasn't parsed properly, it's probably not valid } if (!$valid) { $validator->validationError($this->name, _t('PhoneNumberField.VALIDATION', "Please enter a valid phone number"), "validation", false); return false; } return true; }
/** * Validate by submitting to external service * * @param Validator $validator Validator * * @return boolean * * @author Sascha Koehler <*****@*****.**>, Sebastian Diel <*****@*****.**> * @since 12.02.2013 */ public function validate($validator) { $valid = false; $checkValue = $_REQUEST[$this->getName() . 'Field']; $fh = fopen($this->getTempDir() . '/' . 'cap_' . $this->getFormIdentifier() . '.txt', "r"); $hash = fgets($fh); $hash2 = md5(strtolower($checkValue)); if ($hash2 == $hash) { $valid = true; } else { $validator->validationError($this->getName(), _t('Form.CAPTCHAFIELDNOMATCH'), "validation", false); } return $valid; }
/** * If this field is required then we require at least the first postal line * along with the town and postcode. Either this has been manually filled * in or, automatically filled in by * * @param Validator $validator * * @return bool */ public function validate($validator) { $name = $this->getName(); if ($validator->fieldIsRequired($name)) { // remove this as a required field as we're doing the checking here. $validator->removeRequiredField($name); $fields = $this->getManualFields(); $postal = $fields->dataFieldByName("{$name}[PostalLine1]"); if (!$postal->Value()) { $validator->validationError($name, _t("AddressFinderField.ENTERAVALIDADDRESS", "Please enter a valid address."), 'PostalLine1', false); return false; } $city = $fields->dataFieldByName("{$name}[City]"); if (!$city->Value()) { $validator->validationError($name, _t("AddressFinderField.ENTERAVALIDCITY", "Please enter a valid city."), "City", false); return false; } $postcode = $fields->dataFieldByName("{$name}[Postcode]"); if (!$postcode->Value()) { $validator->validationError($name, _t("AddressFinderField.ENTERAVALIDPOSTCODE", "Please enter a valid postcode."), "Postcode", false); return false; } } return true; }
/** * Validation for this field. * * @param Validator $validator * * @return bool */ public function validate($validator) { if (!$this->value) { return true; } $validationChecks = [true]; if (!$this->isNumeric()) { $validator->validationError($this->name, _t('NumericField.VALIDATION', "'{value}' is not a number, only numbers can be accepted for this field", ['value' => $this->value]), 'validation'); $validationChecks[] = false; } if (($this->getUIOption('max') || $this->getUIOption('max') === 0) && $this->getEnforceAboveMaxValidation() && $this->value > $this->getUIOption('max')) { $validator->validationError($this->name, _t('SpinnerField.ABOVEMAX', '\'{value}\' exceeds the maximum allowed number {max}', ['value' => $this->value, 'max' => $this->getUIOption('max')]), 'validation'); $validationChecks[] = false; } if (($this->getUIOption('min') || $this->getUIOption('min') === 0) && $this->getEnforceBelowMinValidation() && $this->value < $this->getUIOption('min')) { $validator->validationError($this->name, _t('SpinnerField.BELOWMIN', '\'{value}\' is below the minimum allowed number {min}', ['value' => $this->value, 'min' => $this->getUIOption('min')]), 'validation'); $validationChecks[] = false; } if ($this->getEnforceStepValidation() && 0 !== $this->value % $this->getUIOption('step')) { $validator->validationError($this->name, _t('SpinnerField.NOTEVENLYDIVISIBLE', '\'{value}\' is not evenly divisible by {step}', ['value' => $this->value, 'step' => $this->getUIOption('step')]), 'validation'); $validationChecks[] = false; } return min($validationChecks); }