/** * Set items constraints * * @return void */ public function initRules() { $this->rules['no_certificado'] = V::numeric()->noWhitespace()->setName('Numero de certificado'); $this->rules['clave'] = V::notEmpty()->noWhitespace()->setName('Contraseña de la llave privada'); }
public function index($params) { Validator::notEmpty()->setName('name')->check($params['name']); Validator::notEmpty()->setName('password')->check($params['password']); $levels = Config::loadData('level'); $this->render('index.php', ['name' => $params['name']]); }
public function __construct(Client $client, $key) { $this->client = $client; $this->key = $key; $baseUrl = $this->client->getConfig('base_uri'); Validator::notEmpty()->url()->endsWith('/')->setName("URL for NewRelic's Insights API must be valid and have a trailing slash")->assert($baseUrl); }
/** * @param $param * @return string * @throws EntityValidationException */ public function password($param) { if (!v::notEmpty()->length(2, 100)->validate($param)) { throw new EntityValidationException('User', 'password', $param, 'length must be between 2 and 100'); } return $param; }
/** * @param $param * @return string * @throws EntityValidationException */ public function fuelTypeName($param) { if (!v::notEmpty()->length(1, 100)->validate($param)) { throw new EntityValidationException('VehicleCSV', 'fuelTypeName', $param, 'length must be between 1 and 100'); } return $param; }
protected function setValidationRules($validator) { $required = new Validator(); $required->notEmpty(); $validator->attribute('name', $required); $validator->attribute('content', $required); }
/** * @param $param * @return string * @throws EntityValidationException */ public function postalCode($param) { if (!v::notEmpty()->length(2, 100)->validate($param)) { throw new EntityValidationException('Address', 'postalCode', $param, 'length must be between 2 and 50'); } return $param; }
private function validateField($parameters, $fieldName) { if (v::key($fieldName)->validate($parameters)) { if (v::notEmpty()->validate($parameters[$fieldName])) { return true; } } return false; }
/** * @param $param * @return string * @throws EntityValidationException */ public function uniqueReference($param) { if (empty($param) || is_null($param)) { return $param; } if (!v::notEmpty()->length(1, 100)->validate((string) $param)) { throw new EntityValidationException('Vendor', 'uniqueReference', $param, 'length must be between 1 and 100'); } return $param; }
protected function postChild($categoryId) { try { v::arr()->key('name', v::string()->notEmpty()->length(1, 300))->key('parent_category', v::notEmpty()->int()->equals($categoryId))->assert($_POST); $newCategory = (object) (['id' => null] + $_POST); $this->collection->persist($newCategory); $this->collection->flush(); header('HTTP/1.1 303 See Other'); header('Location: ' . $_SERVER['REQUEST_URI']); } catch (NestedValidationExceptionInterface $e) { return ['category/editCategory' => $editProduct, 'messages' => $e->findMessages(['name' => 'Name must have between 1 and 300 chars'])]; } }
public function validateAddress($address) { //@TODO: properly check all types.. strings need to be double checked for alnum, cause of typecasting. $rules = v::key('firstname', v::notEmpty()->setName('First name'))->key('lastname', v::notEmpty()->setName('Last name'))->key('address', v::alnum(".,-'")->notEmpty()->setName('Address'))->key('secondary_address', v::when(v::notEmpty(), v::alnum(".,-'"), v::alwaysValid())->setName('Address 2'))->key('city', v::alnum()->notEmpty()->setName('City'))->key('state', v::alnum()->notEmpty()->setName('State'))->key('zip', v::when(v::notEmpty(), v::postalCode('US'), v::alwaysValid())->notEmpty()->setName('Zipcode')); if ($rules->validate($address)) { return true; } try { $rules->check($address); } catch (ValidationExceptionInterface $exception) { // $this->error = $exception->getMainMessage(); } return false; }
public function test_findMessages_should_apply_templates_to_flattened_messages() { $stringMax256 = v::string()->length(5, 256); $alnumDot = v::alnum('.'); $stringMin8 = v::string()->length(8, null); $v = v::allOf(v::attribute('first_name', $stringMax256)->setName('First Name'), v::attribute('last_name', $stringMax256)->setName('Last Name'), v::attribute('desired_login', $alnumDot)->setName('Desired Login'), v::attribute('password', $stringMin8)->setName('Password'), v::attribute('password_confirmation', $stringMin8)->setName('Password Confirmation'), v::attribute('stay_signedin', v::notEmpty())->setName('Stay signed in'), v::attribute('enable_webhistory', v::notEmpty())->setName('Enabled Web History'), v::attribute('security_question', $stringMax256)->setName('Security Question'))->setName('Validation Form'); try { $v->assert((object) array('first_name' => 'fiif', 'last_name' => null, 'desired_login' => null, 'password' => null, 'password_confirmation' => null, 'stay_signedin' => null, 'enable_webhistory' => null, 'security_question' => null)); } catch (ValidationException $e) { $messages = $e->findMessages(array('allOf' => 'Invalid {{name}}', 'first_name.length' => 'Invalid length for {{name}} {{input}}')); $this->assertEquals($messages['allOf'], 'Invalid Validation Form'); $this->assertEquals($messages['first_name_length'], 'Invalid length for "fiif" fiif'); } }
public function __construct($data) { parent::__construct(); $this->data = $data; $this->fields = array('firstname' => array('value' => $this->data['firstname'], 'validators' => array('notEmpty'), 'errors' => array('Firstname is empty')), 'email' => array('value' => $this->data['email'], 'validators' => array('email', 'notEmpty'), 'errors' => array('Email is not valid', 'Email is empty')), 'url' => array('value' => $this->data['url'], 'validators' => array('notEmpty', 'url'), 'errors' => array('Url is empty', 'Url is not valid')), 'cv' => array('value' => $_FILES['cv'], 'validators' => function () { return v::exists()->validate($_FILES['cv']["tmp_name"]); }, 'errors' => array('File is empty')), 'content' => array('value' => $this->data['content'], 'validators' => function ($value) { return v::when(v::int(), v::positive(), v::notEmpty())->validate($value); }, 'errors' => array('content is not valid')), 'int' => array('value' => $this->data['int'], 'validators' => function ($value) { return v::allOf(v::int(), v::positive(), v::notEmpty())->validate($value); }, 'errors' => array('int is not valid')), 'uppercase' => array('value' => '', 'validators' => function ($value) { return v::string()->uppercase()->validate($value); }, 'errors' => array('uppercase is not valid'))); }
public function validate($addr) { $this->clearErrors(); // Do our special validations first // State should only be set for the US if ($addr->getField('Country') != 'US' && v::notEmpty()->validate($addr->getField('State'))) { $this->addError('State', $this->STATE_ONLY_FOR_US); } // Country must be an ISO3166-1 Country Code if (!array_key_exists($addr->getField('Country'), Iso3166::get())) { $this->addError('Country', $this->COUNTRY_VALID_CODE); } // Perform some general validations and return ourself return parent::validate($addr); }
/** * @RPC\Route("/api/auth/login") * @RPC\Method("POST") */ public function login() { $credentials = json_decode($this->request->getContent(), true); try { v::create()->key('email', v::notEmpty())->key('password', v::notEmpty())->assert($credentials); } catch (ValidationException $e) { $errors = $e->findMessages(['email', 'password']); throw new \pmill\Doctrine\Rest\Exception\ValidationException($errors); } $password = $credentials['password']; unset($credentials['password']); /** @var User $user */ $user = $this->authenticationService->authenticateWithCredentials(User::class, $credentials, $password); $token = $this->authenticationService->generateTokenFromObject($user); return ['token' => $token]; }
private static function ProblemaValido($request) { $tituloValidator = validator::notEmpty()->alnum()->length(4, 15); $problemaValidator = validator::notEmpty()->length(100, 1024 * 5); $entradaValidator = validator::notEmpty()->alnum("()")->length(3, 50); $salidaValidator = validator::notEmpty()->alnum("()")->length(3, 50); if (array_key_exists("titulo", $request)) { $tituloValidator->check($request["titulo"]); } else { throw new InvalidArgumentException("Falta titulo"); } if (array_key_exists("problema", $request)) { $problemaValidator->check($request["problema"]); } else { throw new InvalidArgumentException("Falta redaccion de problema"); } if (!array_key_exists("tiempoLimite", $request)) { throw new InvalidArgumentException("Falta tiempolimite"); } return true; }
$userName = $_POST[username]; $password = $_POST[password]; $unidade = $_POST[unidade]; $name = $_POST[name]; $email = $_POST[email]; //Validation using respect/validation $valid = true; if (!v::noWhitespace()->length(4, 20)->notEmpty()->validate($userName)) { $userNameError = "Por favor digite novamente o nome de usuário, entre 4 e 20 caracteres, sem espaços em branco"; $valid = false; } if (!v::notEmpty()->validate($password)) { $passwordError = "Por favor digite a senha não pode ficar em branco"; $valid = false; } if (!v::notEmpty()->length(1, 5)->validate($unidade)) { $unidadeError = "Por favor digite novamente o unidade, no formato A-00 (letra, traço e número)"; $valid = false; } if (!v::length(3, 80)->notEmpty()->validate($name)) { $nameError = "Por favor digite novamente o nome do morador, entre 3 e 80 caracteres"; $valid = false; } if (!v::email()->validate($email)) { $emailError = "O e-mail informado não é válido."; $valid = false; } if ($valid) { $instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $date = date('Y-m-d H:i:s'); //2015-10-15 15:12:23
/** * Get Fields Definitions * * @access public * @return array */ protected function getFieldDefinitions() { return ['auth_id' => ['Authorisation ID', V::notEmpty()->numeric()], 'auth_pass' => ['Authorisation Password', V::notEmpty()->string()], 'card_num' => ['Card Number', V::notEmpty()->string()->length(16, 16)->digit()->noWhitespace()->creditCard()], 'card_cvv' => ['Card CVV', V::notEmpty()->string()->length(3, 3)->digit()->noWhitespace()], 'card_start' => ['Card Start Date', V::date('my')], 'card_issue' => ['Card Issue Number', V::string()->length(null, 2)->digit()->noWhitespace(), ''], 'card_expiry' => ['Card Expiry Date', V::notEmpty()->date('my')], 'cust_name' => ['Customer Name', V::notEmpty()->string()], 'cust_address' => ['Customer Address', V::notEmpty()->string()], 'cust_postcode' => ['Customer Postcode', V::notEmpty()->string()], 'cust_country' => ['Customer Country', V::notEmpty()->string()->countryCode()], 'cust_ip' => ['Customer IP Address', V::notEmpty()->string()->ip(), $_SERVER['REMOTE_ADDR']], 'cust_email' => ['Customer Email Address', V::notEmpty()->string()->email()], 'cust_tel' => ['Customer Telephone Number', V::notEmpty()->string()->phone()], 'tran_ref' => ['Transaction Reference', V::notEmpty()->string()], 'tran_desc' => ['Transaction Description', V::notEmpty()->string()], 'tran_amount' => ['Transaction Amount', V::notEmpty()->float()->min(1.0)], 'tran_currency' => ['Transaction Currency', V::notEmpty()->string()->length(3, 3)->alpha()->noWhitespace()], 'tran_testmode' => ['Test Mode', V::notEmpty()->bool(), false], 'primary_recipient_dob' => ['Date of Birth (of Primary Recipient)', V::date('Ymd')], 'primary_recipient_surname' => ['Surname (of Primary Recipient)', V::string()->length(2, 64)->alpha('-'), ''], 'primary_recipient_postcode' => ['Postcode (of Primary Recipient)', V::string()->length(2, 16)->alnum(), ''], 'primary_recipient_account_number' => ['Account Number (of Primary Recipient)', V::string()->length(1, 32)->alnum('+-'), '']]; }
private function assertName($name) { Validator::notEmpty()->assert($name); Validator::type('string')->assert($name); Validator::regex('/^[A-Za-z_]+$/')->assert($name); }
protected function getValidationRules() { v::with('app\\Models\\Validation\\'); return [v::attribute('name', v::notEmpty()->alpha()->length(2, 100)->UniqueDimensionUOMName()), v::attribute('symbol', v::notEmpty()->alpha()->length(2, 2)->UniqueDimensionUOMSymbol()), v::attribute('routeTransaction', v::instance('app\\Models\\RouteTransaction')), v::attribute('statusId', v::notEmpty()->int()->positive()), v::attribute('createdAt', v::notEmpty()->date()), v::attribute('expiresAt', v::notEmpty()->date())]; }
private function validateForm($params) { if (!v::notEmpty()->validate($params['first_name'])) { return ['isValid' => false, 'message' => 'First name is required.']; } if (!v::notEmpty()->validate($params['last_name'])) { return ['isValid' => false, 'message' => 'Last name is required.']; } if (!v::notEmpty()->validate($params['email'])) { return ['isValid' => false, 'message' => 'Email is required.']; } if (!v::email()->validate($params['email'])) { return ['isValid' => false, 'message' => 'Business Email should be a valid email.']; } if (!v::notEmpty()->validate($params['password'])) { return ['isValid' => false, 'message' => 'Password is required.']; } if (!v::equals($params['confirm_password'])->validate($params['password'])) { return ['isValid' => false, 'message' => 'Password mismatched.']; } return ['isValid' => true, 'message' => 'User saved.']; }
/** * @PrePersist * @PreUpdate */ public function validate() { v::float()->assert($this->amount); v::numeric("+")->startsWith("+")->assert($this->phone); v::notEmpty()->assert($this->status); }
public function validate($item) { $metaData = Transaction::get('array'); foreach ($this->fieldsToCheck as $field) { if (is_a($this, 'Academe\\SagePay\\Validator\\Model\\Address')) { // I'm assuming/hoping that Billing and Delivery validation rules are identical $data = $metaData['Billing' . $field]; } else { $data = $metaData[$field]; } $value = $item->getField($field); if ($this->hasError($field)) { // We only store one error per field, so if we have already got an error for this // field then don't waste time checking others. This also means that we can have // more specific fields in the child objects which over-ride these completly. continue; } // State is only used when the country is US, the validation rules stores assume country is US. // so here we tweak them. if ($field == 'State' && $item->getField('Country') != 'US') { $data['required'] = false; $data['min'] = 0; $data['max'] = 0; } // If the item is required, check it's not empty if ($data['required'] && !v::notEmpty()->validate($value)) { if ($field == 'PostCode') { // Add an exception for Postcodes when the country is one which does not have postcodes if (!in_array($item->getField('Country'), $this->countriesWhichDontHavePostcodes)) { $this->addError($field, sprintf($this->CANNOT_BE_EMPTY, $field)); } } else { if ($field == 'Amount') { // 0 equates to empty, so do a special check if ($item->getField('Amount') != '0' && !v::string()->notEmpty()->validate($item->getField('Amount'))) { $this->addError($field, sprintf($this->CANNOT_BE_EMPTY, $field)); } } else { $this->addError($field, sprintf($this->CANNOT_BE_EMPTY, $field)); } } } // If there is a minimum or maximum check the length. // TODO: Check whether this code works well when only one or the other is set $min = isset($data['min']) ? $data['min'] : null; $max = isset($data['max']) ? $data['max'] : null; if ($min != null && $max != null) { // Check the length of the field if ($field == 'State') { print_r("\n\nMin: {$field} : {$min}, \n\n"); die; } if (!v::length($min, $max, true)->validate($value)) { if ($min == $max) { $this->addError($field, sprintf($this->BAD_LENGTH, $field, $min)); } else { $this->addError($field, sprintf($this->BAD_RANGE, $field, $min, $max)); } } } // Check the contents of the field if (isset($data['chars'])) { // We build two regexes, one for testing whether it matches and the other for // filtering out the bad characters to show the user which are not valid. $regex = $this->buildRegex($data['chars']); try { if (!v::regex($regex)->validate($value)) { $cleanupRegex = $this->buildRegex($data['chars'], false); $badChars = preg_replace($cleanupRegex, '', $value); $this->addError($field, sprintf($this->BAD_CHARACTERS, $field, $badChars, $regex)); } } catch (\Exception $e) { throw new \Exception("preg_match has a problem with this regex '{$regex}'"); } } } return $this; }
protected function _configure() { $this->_addValidator('name', Validator::notEmpty()->length(2, 32)); $this->_addValidator('testField', Validator::string()->endsWith('test')); }
public static function isPositiveInt($num) { return v::notEmpty()->int()->positive()->validate($num); }
/** * Informa a descrição da operação * * @access public * @param string $descricao * @return Cielo */ public function setDescricao($descricao) { if (!v::notEmpty()->validate($descricao)) { throw new InvalidArgumentException(sprintf('Descrição %s é inválido.', $descricao)); } $this->descricao = $descricao; return $this; }
/** * Configura o número do cartão * * @access public * @param string $cartao * @return Cartao */ public function setCartao($cartao) { if (!v::notEmpty()->creditCard()->validate($cartao)) { throw new InvalidArgumentException('O número do cartão deve ser válido.'); } $this->cartao = filter_var($cartao, FILTER_SANITIZE_NUMBER_INT); return $this; }
/** * @inheritdoc */ public function setTitle(string $title) { try { v::notEmpty()->assert($title); $this->title = $title; } catch (AllOfException $e) { throw new InvalidArgumentException('Title is invalid'); } }
public function upsertUserProcessAction() { $id = $_POST['id'] ?? null; if ($id && !ctype_digit($id)) { $this->flasher->error('E01 Invalid user ID: ' . $id); $this->redirect('/users'); } $user = null; if ($id) { $user = Gatekeeper::findUserById($id); if (!$user) { $this->flasher->error('E02 Invalid user ID: ' . $id); } } // Validation try { v::alnum('- .')->setName('First name')->check($_POST['firstName']); v::alnum('- .')->setName('Last name')->check($_POST['lastName']); v::email()->setName('Email')->check($_POST['email']); if (!$user) { v::notEmpty()->setName('Password')->check($_POST['password']); } $_POST['username'] = $_POST['email']; $_POST['groups'] = array_map('intval', array_filter($_POST['groups'])); } catch (ValidationException $e) { $this->flasher->error($e->getMainMessage()); echo $this->twig->render('users/upsert.twig', ['flashes' => $this->flasher->display(), 'user' => $user ?: $_POST, 'groups' => $this->gk_groups]); return false; } if ($user) { $user->firstName = $_POST['firstName']; $user->lastName = $_POST['lastName']; $user->email = $_POST['email']; $user->username = $_POST['email']; if (!empty($_POST['password'])) { $user->password = $_POST['password']; } $user->save(); foreach ($user->groups as $group) { $user->revokeGroup($group->id); } foreach ($_POST['groups'] as $group) { $user->addGroup($group); } (bool) $_POST['active'] ?? false ? $user->activate() : $user->deactivate(); $this->flasher->success('Successfully updated user.'); $this->redirect('/users/add/' . $user->id); } else { $groups = $_POST['groups']; unset($_POST['groups']); if ($user = Gatekeeper::register($_POST)) { foreach ($groups as $group) { $user->addGroup($group); } } if (Gatekeeper::getLastError()) { $this->flasher->error($this->site['debug'] ? Gatekeeper::getLastError() : "Could not create user!"); echo $this->twig->render('users/upsert.twig', ['flashes' => $this->flasher->display(), 'user' => $user ?: $_POST, 'groups' => $this->gk_groups]); return false; } $this->flasher->success('Successfully created user.'); $this->redirect('/users'); } return true; }
public static function required($details, $value) { // required==FALSE if ($details === FALSE) { return TRUE; } if (is_array($value)) { return count($value) > 0; } else { if ($value === '0') { // Zero as a string is valid return TRUE; } else { return RespectValidator::notEmpty()->validate((string) $value); } } }