/** * @param mixed $entity * @param bool $valid * @dataProvider validatorDataProvider */ public function testValidator($entity, $valid) { $errors = $this->validator->validate($entity); if ($valid) { $this->assertCount(0, $errors, 'Entity should be valid: ' . var_export($entity, true)); $this->assertNull($entity->getId()); } else { $this->assertGreaterThan(0, count($errors), 'Entity should not be valid: ' . var_export($entity, true)); } }
/** * sava data object to database * * @throws ValidatorException it is thrown if objects data are wrong */ public function save() { self::setUpConnection(); $this->_validator->validate($this); if (isset($this->_data['id']) && is_numeric($this->_data['id'])) { $this->update(); } else { $this->insert(); } }
public function testValidate() { $className = 'Same\\Class\\Name'; $validator1 = $this->getMock('Magento\\Framework\\Code\\ValidatorInterface'); $validator1->expects($this->once())->method('validate')->with($className); $validator2 = $this->getMock('Magento\\Framework\\Code\\ValidatorInterface'); $validator2->expects($this->once())->method('validate')->with($className); $this->model->add($validator1); $this->model->add($validator2); $this->model->validate($className); }
/** * Checks if a locale is allowed and valid * * @param string $locale * * @return bool */ public function isAllowed($locale) { if ($this->validator instanceof ValidatorInterface2dot5) { $errorListLocale = $this->validator->validate($locale, new Locale()); $errorListLocaleAllowed = $this->validator->validate($locale, new LocaleAllowed()); } else { $errorListLocale = $this->validator->validateValue($locale, new Locale()); $errorListLocaleAllowed = $this->validator->validateValue($locale, new LocaleAllowed()); } return count($errorListLocale) == 0 && count($errorListLocaleAllowed) == 0; }
/** * @dataProvider getObjectsToValidate */ public function testValidateObject($object, $violationCount, $groups = array()) { if (0 === count($groups)) { $groups = null; } if ($this->validator instanceof ValidatorInterface) { $this->assertEquals($violationCount, $this->validator->validate($object, null, $groups)->count()); } else { $this->assertEquals($violationCount, $this->validator->validate($object, $groups)->count()); } }
public function validate($form, $field = NULL) { parent::validate($form, $field); reset($this->rules); $nan = key($this->rules); next($this->rules); $min = key($this->rules); next($this->rules); $max = key($this->rules); next($this->rules); $val = $field->value(); if (isset($val) && !is_numeric($val)) { $this->errors[] = $this->rules[$nan]; return FALSE; } if (isset($val) && $val < $min) { $this->errors[] = $this->rules[$min]; return FALSE; } if (isset($val) && $val > $max) { $this->errors[] = $this->rules[$max]; return FALSE; } return TRUE; }
public function testValidateNegative() { $history = $this->getMock('Magento\\Sales\\Model\\Order\\Status\\History', ['hasData'], [], '', false); $history->expects($this->any())->method('hasData')->with('parent_id')->will($this->returnValue(false)); $validator = new Validator(); $this->assertEquals(['Order Id is a required field'], $validator->validate($history)); }
/** * Processing that occurs before a form is executed. * * This includes form validation, if it fails, we redirect back * to the form with appropriate error messages. * Always return true if the current form action is exempt from validation * * Triggered through {@link httpSubmission()}. * * Note that CSRF protection takes place in {@link httpSubmission()}, * if it fails the form data will never reach this method. * * @return boolean */ public function validate() { $buttonClicked = $this->buttonClicked(); if ($buttonClicked && in_array($buttonClicked->actionName(), $this->getValidationExemptActions())) { return true; } if ($this->validator) { $errors = $this->validator->validate(); if ($errors) { // Load errors into session and post back $data = $this->getData(); // Encode validation messages as XML before saving into session state // As per Form::addErrorMessage() $errors = array_map(function ($error) { // Encode message as XML by default if ($error['message'] instanceof DBField) { $error['message'] = $error['message']->forTemplate(); } else { $error['message'] = Convert::raw2xml($error['message']); } return $error; }, $errors); Session::set("FormInfo.{$this->FormName()}.errors", $errors); Session::set("FormInfo.{$this->FormName()}.data", $data); return false; } } return true; }
public function sendEmail() { try { $emails = explode(',', $this->_correo); $to = []; foreach ($emails as $email) { $params = ['mail' => ['requerido' => 1, 'validador' => 'esEmail', 'mensaje' => utf8_encode('El correo no es válido.')]]; $destinatario = ['name' => $email, 'mail' => $email]; $form = new Validator($destinatario, $params); if ($form->validate() === false) { throw new Exception('El correo ' . $email . ' no es válido.'); } $to[] = $destinatario; } $this->_template = ParserTemplate::parseTemplate($this->_template, $this->_info); // $subject = '', $body = '', $to = array(), $cc = array(), $bcc = array(), $att = array() if (Mailer::sendMail($this->_subject, $this->_template, $to, $this->_cc)) { return true; } else { return false; } } catch (phpmailerException $e) { $this->_PDOConn->rollBack(); return false; } }
public static function edit($data) { $p = array('title' => array('required' => true, 'type' => 'string', 'maxlength' => 140, 'label' => 'Titulo'), 'text' => array('required' => true, 'type' => 'string', 'label' => 'Texto'), 'image' => array('required' => false, 'type' => 'thumbnail', 'label' => 'Imagen'), 'tags' => array('required' => false, 'type' => 'string', 'label' => 'Tags')); $v = new Validator(); $response = $v->validate($data, $p); if (!$response['success']) { return M::cr(false, $data, $response['msg']); } PDOSql::$pdobj = pdoConnect(); if (isset($_FILES['image']['name'])) { $response = File::up2Web($_FILES['image']); if ($response->success) { // remove old image... if (isset($data['old_image'])) { File::unlinkWeb($data['old_image']); } $image = $response->data[0]; } else { return M::cr(false, $data, $response->msg); } } else { $image = ''; } $params = array($data['title'], $data['text'], $image, $data['tags'], $data['id'], $_SESSION['userNAME']); $where = array(' id = ?', 'author = ?'); $query = "UPDATE entries SET title = ?, text = ?, image = ?, tags = ? {%WHERE%}"; PDOSql::update($query, $params, $where); return M::cr(true, array(), 'Se han actualizado los datos correctamente'); }
static function validate(&$values, $validators, $defaults = array(), $names = array()) { $filtered_values = array(); foreach ($validators as $name => $options) { if (!isset($values[$name])) { $values[$name] = null; } if (!$options) { $options = array(); } $validator = new Validator($options); $validator->setOption('required', true); if (!isset($options['array']) || $options['array'] === false) { $valid = !is_array($values[$name]) && $validator->validate($values[$name]); } else { $valid = is_array($values[$name]) && $validator->validateArray($values[$name]); } $key_name = isset($names[$name]) ? $names[$name] : $name; if ($valid) { $filtered_values[$key_name] = $values[$name]; } else { if (isset($defaults[$name])) { $filtered_values[$key_name] = $defaults[$name]; } else { $filtered_values[$key_name] = null; } } } return $values = $filtered_values; }
/** * Get a delivery label for a parcel and a recipient * * @param array $parcel * @param array $recipient * @param array $sender * @param boolean $validate * * @throws InvalidRequestException * @throws FailedRequestException * @throws \SoapFault * * @return ReturnLetter */ public function getLabel(array $parcel, array $recipient, array $sender = array(), $validate = true) { $request = $this->buildLetterColissimoRequest($parcel, $recipient, $sender); if ($validate) { $violations = $this->validator->validate($request->getLetter()); if ($violations->count() > 0) { $exception = new InvalidRequestException('The request is not valid, please check the violations list'); $exception->setViolations($violations); throw $exception; } } $response = $this->client->getLetterColissimo($request); if (!$response->isSuccess()) { throw new FailedRequestException($response->getErrorMessage()); } return $response->getReturnLetter(); }
public function validate($form, $field = NULL) { parent::validate($form, $field); $value = $field->value(); if (isset($value) && !filter_var($value, FILTER_VALIDATE_EMAIL)) { $this->errors[] = $this->errorMessage; } return !$this->errors; }
public function isValid() { $validator = new Validator($this->getData()); $check = $validator->validate($this->getRules()); if (!$check) { $this->setErrors($validator->errors); } return $check; }
public function form_handler() { $validator = new Validator($_POST); $validator->setRules('name', 'Name', 'minLength[4]|maxLength[8]'); $validator->setRules('date', 'Date', 'dateRange[ 12/27/10, 12/28/10 ]'); if ($validator->validate()) { $validator->storeSuccessMessage('Success!'); } Util::redirect('admin', true); }
public function validate($form, $field = NULL) { parent::validate($form, $field); $value = $field->value(); foreach ($this->rules as $rule => $error) { if (isset($value) && !preg_match($rule, $value)) { $this->errors[] = $error; } } return !$this->errors; }
/** * 验证数据 */ public function validate($data) { $fields = self::getFields(); $validator = new Validator($fields, $data); $this->data = $validator->validate(); if (!$this->data) { $this->errors = $validator->getErrors(); return false; } return true; }
/** * @noAuth * @url POST /?submissions * @url PUT /?submissions/$id */ function insertSubmission($id = null, $data) { if ($data == null) { $data = $_POST; } else { $data = get_object_vars($data); } //var_dump($data); //check if file submitted $file = false; if (isset($_FILES['file']) && !empty($_FILES['file']['name']) && $_FILES['file']['size'] > 0) { $file = $_FILES['file']; $data['image_result'] = $file['name']; } //validate $validationRules = array(); if (isset($data['text_question']) && !empty($data['text_question'])) { $validationRules['text_result'] = VALIDATE_RULE_NON_EMPTY_STRING | VALIDATE_RULE_REQUIRED; } if (isset($data['image_question']) && !empty($data['image_question'])) { $validationRules['image_result'] = VALIDATE_RULE_NON_EMPTY_STRING | VALIDATE_RULE_REQUIRED; } $validator = new Validator($data); $errors = $validator->validate($validationRules); if (!empty($errors)) { throw new RestException(400, implode(" ", $errors)); } //add new entry if ($id == null) { //insert into database $db = new SubmissionDatabase(); $db->insertSubmission($data); $id = $db->lastInsertRowid(); //upload file if ($file) { $upload_dir = DIR_SUBMISSION_FILES . '/' . $id; try { checkFileType($file['name'], array("jpg", "jpeg", "gif", "png")); uploadFile($file['tmp_name'], $upload_dir, $file['name']); } catch (Exception $e) { // delete entry if upload failed $db->deleteSubmission($id); throw new RestException(400, $e->getMessage()); } } return $db->getSubmission($id); // modify entry } else { //insert Model and return it $db = new SubmissionDatabase(); $db->insertSubmission($data); return $db->getSubmission($id); } }
function validate($data) { // check the rules created in the constructor if (!parent::validate($data)) { return false; } // and if they succeeded, check if the file exists. If not, return false // and go to the main page... $filePath = "templates/summary/{$data}.template"; return File::isReadable($filePath); }
public function testHoneypot() { $validator = new Validator(); // test pass $form = new \HtmlForm\Form(); $form->addHoneypot(); $result = $validator->validate($form); $this->assertFalse($validator->honeypotError); // test fail $result = $validator->honeypot("string"); $this->assertTrue($validator->honeypotError); }
public function validate(Validatable $field) { if (!parent::validate($field)) { return false; } $value = $field->getValue(); if (!is_numeric($value) || $value < $this->min || $value > $this->max) { $field->setError('moet een getal tussen ' . $this->min . ' en ' . $this->max . ' zijn'); return false; } return true; }
public function validate($form, $field = NULL) { parent::validate($form, $field); $value = $field->value(); if (is_scalar($value) && !strlen($value)) { $this->errors[] = $this->errorMessage; } else { if (!is_scalar($value) && !$value) { $this->errors[] = $this->errorMessage; } } return !$this->errors; }
/** * Validate requst if $autoValidate equals true * * @return void */ protected function vilidateRequest() { if (array_key_exists($this->action, $this->validateRules)) { $args = array_merge($this->post, $this->query); if (count($args) > 0) { $res = $this->validator->validate($args); if ($res == false) { $this->session->errors = $this->validator->getError(); $this->redirect(sprintf('%s/%s', $this->controller, $this->session->back_action)); } } } }
/** * Processing that occurs before a form is executed. * * This includes form validation, if it fails, we redirect back * to the form with appropriate error messages. * * Triggered through {@link httpSubmission()}. * * Note that CSRF protection takes place in {@link httpSubmission()}, * if it fails the form data will never reach this method. * * @return boolean */ public function validate() { if ($this->validator) { $errors = $this->validator->validate(); if ($errors) { // Load errors into session and post back $data = $this->getData(); Session::set("FormInfo.{$this->FormName()}.errors", $errors); Session::set("FormInfo.{$this->FormName()}.data", $data); return false; } } return true; }
public function validate(Validatable $field) { if ($field->getValue() == '' && !$this->required) { return true; } if (parent::validate($field)) { if (preg_match('/^[^@]+@[a-zA-Z0-9._-]+\\.[a-zA-Z]+$/', $field->getValue()) != 1) { $field->setError('is geen geldig e-mailadres'); return false; } return true; } return false; }
private function Validate() { $validation = new Validator(); //$validation->AddEmailValidation(); //$validation->AddPasswordValidation(); $validationMessages = $validation->validate($_POST); if (count($validationMessages)) { foreach ($validationMessages as $message) { echo $message, '<br>'; } echo $this->tag->linkTo("login", "Go back"); return false; } return true; }
public function validate(Validatable $field) { if ($this->required) { if (!parent::validate($field)) { return false; } } $length = strlen($field->getValue()); if ($this->required || $length > 0 && !is_null($field->getValue())) { if ($length < $this->minLength || $length > $this->maxLength) { $field->setError('mag minimaal ' . $this->minLength . ' en maximaal ' . $this->maxLength . ' tekens bevatten'); return false; } } return true; }
public function update($args) { if (!Token::match(Input::get('_token'))) { return Redirect::back(); } $v = new Validator(); $v->validate(Input::all(), ['title' => 'required|min:3', 'body' => 'required']); if (!$v->passed()) { return Redirect::back(['key' => 'errors', 'values' => $v->errors()]); } $id = $args['id']; $post = $this->post->update($id, ['title' => Input::get('title'), 'body' => Input::get('body')]); if ($post) { Session::flash('success', 'Successfully updated a post.'); return Redirect::to('/'); } }
/** * @noAuth * @url POST /?documents * @url PUT /?documents/$id */ function insertDocument($id = null) { //validate post data $validator = new Validator($_POST); $errors = $validator->validate(array('title' => VALIDATE_RULE_REQUIRED | VALIDATE_RULE_NON_EMPTY_STRING, 'author' => VALIDATE_RULE_REQUIRED | VALIDATE_RULE_NON_EMPTY_STRING, 'published' => VALIDATE_RULE_YEAR, 'keywords' => VALIDATE_RULE_REQUIRED, 'isbn' => VALIDATE_RULE_ISBN)); if (!empty($errors)) { throw new RestException(400, implode(" ", $errors)); } //change string cases $_POST['title'] = ucfirst($_POST['title']); $_POST['author'] = ucwords($_POST['author']); $_POST['keywords'] = strtolower($_POST['keywords']); // submit new entry and upload file if ($id == null) { if (!isset($_FILES['file']) || empty($_FILES['file']['name'])) { throw new RestException(400, 'No File submitted'); } $file = $_FILES['file']; if ($file['size'] < 1 || $file['size'] > UPLOAD_FILE_MAX_SIZE) { throw new RestException(400, "File is too large, maximum file size is " . strval(UPLOAD_FILE_MAX_SIZE / 8 / 1024 / 1024) . " MB."); } // append filename to post data and insert in database $db = new DocumentsDatabase(); $_POST['file'] = $file['name']; $db->insertDocument($_POST); //upload file $id = $db->lastInsertRowid(); $upload_dir = DIR_RECORD_FILES . '/' . $id; try { checkFileType($file['name']); uploadFile($file['tmp_name'], $upload_dir, $file['name']); } catch (Exception $e) { // delete entry if upload failed $db->deleteDocument($id); throw new RestException(400, $e->getMessage()); } return $db->getDocument($id); // modify entry } else { //insert Model and return it $db = new DocumentsDatabase(); $db->insertDocument($_POST); return $db->getDocument($id); } }
/** * Processing that occurs before a form is executed. * * This includes form validation, if it fails, we redirect back * to the form with appropriate error messages. * Always return true if the current form action is exempt from validation * * Triggered through {@link httpSubmission()}. * * Note that CSRF protection takes place in {@link httpSubmission()}, * if it fails the form data will never reach this method. * * @return boolean */ public function validate() { $buttonClicked = $this->buttonClicked(); if ($buttonClicked && in_array($buttonClicked->actionName(), $this->getValidationExemptActions())) { return true; } if ($this->validator) { $errors = $this->validator->validate(); if ($errors) { // Load errors into session and post back $data = $this->getData(); Session::set("FormInfo.{$this->FormName()}.errors", $errors); Session::set("FormInfo.{$this->FormName()}.data", $data); return false; } } return true; }