本文整理汇总了PHP中Respect\Validation\Validator::length方法的典型用法代码示例。如果您正苦于以下问题:PHP Validator::length方法的具体用法?PHP Validator::length怎么用?PHP Validator::length使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Respect\Validation\Validator
的用法示例。
在下文中一共展示了Validator::length方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: post
public function post($request, $response, $service, $app)
{
Auth::restrictAccess('anonymous');
$app->users = new Users();
$app->passwordResets = new PasswordResets();
$email = $request->param('email');
$token = $request->param('token');
$passwordReset = self::validatePasswordResetRequest($email, $token);
$body = json_decode($request->body());
$newPassword = $body->newPassword;
$confirmPassword = $body->confirmPassword;
if (!v::length(6, 55)->validate($newPassword)) {
return 'password 1 dont comply';
}
if (!v::length(6, 55)->validate($confirmPassword)) {
return 'password 2 dont comply';
}
if (!v::equals($newPassword)->validate($confirmPassword)) {
return 'passwords dont match';
}
// user update password
$app->users->updatePassword($passwordReset['userId'], $newPassword);
// delete the passwordReset row after use
$app->passwordResets->destroy($passwordReset['id']);
}
示例2: create
/**
* Creates a new {@link LightInstruction}, verifying the action is valid and exactly two
* coordinates have been given.
*
* @param int $action {@link LightInstructionAction}
* @param Coordinate[] $coordinatePair two coordinates
* @return LightInstruction
* @throws \InvalidArgumentException
*/
public static function create($action, array $coordinatePair)
{
v::oneOf(v::equals(LightInstructionAction::TURN_ON), v::equals(LightInstructionAction::TURN_OFF), v::equals(LightInstructionAction::TOGGLE))->check($action);
v::length(2, 2)->check($coordinatePair);
v::each(v::instance('\\Hamdrew\\AdventOfCode\\Day6\\Coordinate'))->check($coordinatePair);
return new LightInstruction($action, $coordinatePair);
}
示例3: __construct
/**
* @param string $category
* @param string|null $subCategory
* @throws InvalidArgumentException
* @throws UserException
*/
public function __construct($category, $subCategory = null)
{
if (!is_string($category)) {
throw new InvalidArgumentException('category', 'type_invalid');
}
if (!mb_check_encoding($category, 'UTF-8')) {
throw new InvalidArgumentException('category', 'encoding_invalid');
}
if (!Validator::length(VJ::TAG_MIN, VJ::TAG_MAX)->validate($category)) {
throw new UserException('Problem.Tag.invalid_length');
}
$keyword = KeywordFilter::isContainGeneric($category);
if ($keyword !== false) {
throw new UserException('Problem.Tag.name_forbid', ['keyword' => $keyword]);
}
if (!is_string($subCategory)) {
throw new InvalidArgumentException('subCategory', 'type_invalid');
}
if (!mb_check_encoding($subCategory, 'UTF-8')) {
throw new InvalidArgumentException('subCategory', 'encoding_invalid');
}
if (!Validator::length(VJ::TAG_MIN, VJ::TAG_MAX)->validate($subCategory)) {
throw new UserException('Problem.Tag.invalid_length');
}
$keyword = KeywordFilter::isContainGeneric($subCategory);
if ($keyword !== false) {
throw new UserException('Problem.Tag.name_forbid', ['keyword' => $keyword]);
}
$this->category = $category;
$this->subCategory = $subCategory;
}
示例4: createDiscussion
/**
* 创建主题
*
* @param \MongoId $topicId
* @param int $owner
* @param string title
* @param string $markdown
* @return array|null
* @throws InvalidArgumentException
* @throws UserException
*/
public static function createDiscussion(\MongoId $topicId, $owner, $title, $markdown)
{
if (!Validator::int()->validate($owner)) {
throw new InvalidArgumentException('owner', 'type_invalid');
}
if (!is_string($title)) {
throw new InvalidArgumentException('markdown', 'type_invalid');
}
if (!mb_check_encoding($title, 'UTF-8')) {
throw new InvalidArgumentException('markdown', 'encoding_invalid');
}
if (!is_string($markdown)) {
throw new InvalidArgumentException('markdown', 'type_invalid');
}
if (!mb_check_encoding($markdown, 'UTF-8')) {
throw new InvalidArgumentException('markdown', 'encoding_invalid');
}
if (!Validator::length(VJ::COMMENT_MIN, VJ::COMMENT_MAX)) {
throw new UserException('DiscussionUtil.content_invalid_length');
}
self::initParser();
$discussionId = new \MongoId();
$html = self::$parser->parse($markdown);
$keyword = KeywordFilter::isContainGeneric(strip_tags($html));
if ($keyword !== false) {
throw new UserException('DiscussionUtil.content_forbid', ['keyword' => $keyword]);
}
$doc = ['_id' => $discussionId, 'owner' => (int) $owner, 'topicId' => $topicId, 'at' => new \MongoDate(), 'title' => $title, 'raw' => $markdown, 'html' => $html];
Application::coll('Discussion')->insert($doc);
Application::emit('discussion.create.succeeded', [$topicId, $discussionId]);
return ['_id' => $discussionId, 'html' => $html];
}
示例5: validate
private function validate()
{
$OPEIDV = v::length(6, 6);
if ($OPEIDV->validate($this->Input->getInput('OPEID')) == false) {
$this->validation_errors[] = 'OPEID should not be empty and have 6 digits.';
}
$CIPCodeV = v::length(7);
if ($CIPCodeV->validate($this->Input->getInput('CIPCode')) == false) {
$this->validation_errors[] = 'CIPCode should follow xx.xxxx format.';
}
}
示例6: testKeysAsValidatorNames
public function testKeysAsValidatorNames()
{
try {
Validator::key('username', Validator::length(1, 32))->key('birthdate', Validator::date())->setName("User Subscription Form")->assert(array('username' => '', 'birthdate' => ''));
} catch (NestedValidationExceptionInterface $e) {
$this->assertEquals('\\-These rules must pass for User Subscription Form
|-Key username must be valid
| \\-"" must have a length between 1 and 32
\\-Key birthdate must be valid
\\-"" must be a valid date', $e->getFullMessage());
}
}
示例7: saveAction
/**
* @auth-groups users
*/
public function saveAction()
{
if (!empty($_POST['password_new'])) {
try {
v::length(6)->check($_POST['password_new']);
} catch (ValidationException $e) {
$this->flasher->error('Please make sure new password is longer than 6 characters!');
}
if ($_POST['password_new'] !== $_POST['password_new_confirm']) {
$this->flasher->error('New password fields were not identical!');
}
if (!Gatekeeper::authenticate(['username' => $this->user->username, 'password' => $_POST['password_old']])) {
$this->flasher->error('Invalid password. Changes ignored.');
} else {
$this->user->password = $_POST['password_new'];
$this->user->save();
$this->flasher->success('Password updated!');
}
}
if ($_POST['firstname'] != '-') {
try {
v::alnum(' ')->check($_POST['firstname']);
$this->user->firstName = $_POST['firstname'];
$this->user->save();
$this->flasher->success('First name changed.');
} catch (ValidationException $e) {
$this->flasher->error('Name contains invalid characters. ' . $e->getMainMessage());
}
}
if ($_POST['lastname'] != '-') {
try {
v::alnum(' ')->check($_POST['lastname']);
$this->user->lastName = $_POST['lastname'];
$this->user->save();
$this->flasher->success('Last name changed.');
} catch (ValidationException $e) {
$this->flasher->error('Last name contains invalid characters. ' . $e->getMainMessage());
}
}
$this->redirect('/account');
}
示例8: processSignupAction
public function processSignupAction()
{
try {
v::email()->check($_POST['email']);
v::length(6)->check($_POST['password']);
} catch (ValidationException $e) {
$this->flasher->error('Please make sure your password is longer than 6 characters, and that your username is a valid email address!');
}
if ($_POST['password'] !== $_POST['password_confirm']) {
$this->flasher->error('Passwords need to be identical');
}
if ($this->flasher->hasMessages('error')) {
$this->redirect('/auth');
}
$this->initGroups();
// Create an account if none exists
$user = Gatekeeper::register(['first_name' => '-', 'last_name' => '-', 'username' => $_POST['email'], 'email' => $_POST['email'], 'password' => $_POST['password'], 'groups' => Gatekeeper::countUser() ? ['users'] : ['admin', 'users']]);
if ($user) {
$this->flasher->success('Account successfully registered! Please log in!');
} else {
$this->flasher->error('Error #GK01: Account creation failed!' . Gatekeeper::getDatasource()->getLastError());
}
$this->redirect('/auth');
}
示例9: __construct
/**
* @param string $name
* @param int|null $year
* @throws InvalidArgumentException
* @throws UserException
*/
public function __construct($name, $year = null)
{
if (!is_string($name)) {
throw new InvalidArgumentException('name', 'type_invalid');
}
if (!mb_check_encoding($name, 'UTF-8')) {
throw new InvalidArgumentException('name', 'encoding_invalid');
}
$keyword = KeywordFilter::isContainGeneric($name);
if ($keyword !== false) {
throw new UserException('Problem.Tag.name_forbid', ['keyword' => $keyword]);
}
if (!Validator::length(VJ::TAG_MIN, VJ::TAG_MAX)->validate($name)) {
throw new UserException('Problem.Tag.invalid_length');
}
if ($year !== null) {
if (!Validator::int()->validate($year)) {
throw new InvalidArgumentException('year', 'type_invalid');
}
$year = (int) $year;
}
$this->name = $name;
$this->year = $year;
}
示例10: validateSoftDescriptor
private function validateSoftDescriptor($parameters)
{
$fieldName = "soft_descriptor";
if (array_key_exists($fieldName, $parameters)) {
if (!v::length(1, 13, true)->validate($parameters[$fieldName]) || !v::alnum()->noWhitespace()->validate($parameters[$fieldName])) {
$this->validationResponse->status = s::VALIDATION_ERROR;
$this->validationResponse->errors[$fieldName] = "is invalid";
return false;
}
}
return true;
}
示例11: prototyper_validate_maxlength
/**
* Validates that input length is greater than the expecation
*
* @param string $hook "validate:maxlength"
* @param string $type "prototyper"
* @param ValidationStatus $validation Current validation status
* @param array $params Hook params
* @return ValidationStatus
*/
function prototyper_validate_maxlength($hook, $type, $validation, $params)
{
if (!$validation instanceof ValidationStatus) {
$validation = new ValidationStatus();
}
$field = elgg_extract('field', $params);
if (!$field instanceof Field) {
return $validation;
}
$rule = elgg_extract('rule', $params);
if ($rule != "maxlength") {
return $validation;
}
$value = elgg_extract('value', $params);
$expectation = elgg_extract('expectation', $params);
if (!v::length(null, $expectation)->validate($value)) {
$validation->setFail(elgg_echo('prototyper:validate:error:maxlength', array($field->getLabel(), $expectation)));
}
return $validation;
}
示例12: createUser
/**
* 创建用户
*
* @param string $username
* @param string $password
* @param string $email
* @return int UID
* @throws InvalidArgumentException
* @throws UserException
*/
public function createUser($username, $password, $email)
{
if (!is_string($username)) {
throw new InvalidArgumentException('username', 'type_invalid');
}
if (!is_string($password)) {
throw new InvalidArgumentException('password', 'type_invalid');
}
if (!is_string($email)) {
throw new InvalidArgumentException('email', 'type_invalid');
}
// 检查用户名
if (!mb_check_encoding($username, 'UTF-8')) {
throw new InvalidArgumentException('username', 'encoding_invalid');
}
$username = trim($username);
if (!Validator::regex('/^\\S*$/')->length(3, 16)->validate($username)) {
throw new InvalidArgumentException('username', 'format_invalid');
}
// 检查关键字
$keyword = KeywordFilter::isContainGeneric($username);
if ($keyword === false) {
$keyword = KeywordFilter::isContainName($username);
}
if ($keyword !== false) {
throw new UserException('UserManager.name_forbid', ['keyword' => $keyword]);
}
// 检查密码
if (!Validator::length(0, 50)->validate($password)) {
throw new InvalidArgumentException('password', 'format_invalid');
}
// 检查 email
if (!Validator::email()->validate($email)) {
throw new InvalidArgumentException('password', 'format_invalid');
}
// 处理用户名
$username = VJ::removeEmoji($username);
// 检查用户名和 Email 是否唯一
if (UserUtil::getUserObjectByUsername($username) !== null) {
throw new UserException('UserManager.createUser.user_exists');
}
if (UserUtil::getUserObjectByEmail($email) !== null) {
throw new UserException('UserManager.createUser.email_exists');
}
// 生成 hash & salt
$hashSaltPair = $this->user_credential->password_encoder->generateHash($password);
// 插入记录
try {
$_id = new \MongoId();
$doc = ['_id' => $_id, 'uid' => $_id, 'user' => $username, 'luser' => UserUtil::canonicalizeUsername($username), 'mail' => $email, 'lmail' => UserUtil::canonicalizeEmail($email), 'salt' => $hashSaltPair['salt'], 'hash' => $hashSaltPair['hash'], 'g' => $email, 'gender' => VJ::USER_GENDER_UNKNOWN, 'regat' => new \MongoDate(), 'regip' => $this->request->getClientIp()];
Application::coll('User')->insert($doc);
} catch (\MongoCursorException $e) {
// 插入失败
throw new UserException('UserManager.createUser.user_or_email_exists');
}
// 插入成功:更新 uid
// 获取递增 uid
$counterRec = Application::coll('System')->findAndModify(['_id' => 'UserCounter'], ['$inc' => ['count' => 1]], [], ['new' => true, 'upsert' => true]);
$uid = (int) $counterRec['count'];
try {
// 修改 uid
Application::coll('User')->update(['_id' => $_id], ['$set' => ['uid' => $uid]]);
} catch (\MongoCursorException $e) {
// 修改 uid 失败(uid 重复),则删除用户记录
Application::critical('createUser.uidDuplicate', ['uid' => $uid]);
Application::coll('User')->remove(['_id' => $_id], ['justOne' => true]);
throw new UserException('UserManager.createUser.internal');
}
Application::emit('user.created', [$uid]);
return $uid;
}
示例13: validate
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;
}
示例14: array
$roleValidator = v::notEmpty();
$companyValidator = v::notEmpty();
$passwordValidator = v::length(6, null);
$validators = array('email' => $emailValidator, 'password' => $passwordValidator);
return new \DavidePastore\Slim\Validation\Validation($validators);
};
$container['registerValidation'] = function () {
//Create the validators
$usernameValidator = v::notEmpty()->alnum()->noWhitespace()->length(1, 10);
$ageValidator = v::numeric()->positive()->between(1, 20);
$emailValidator = v::email()->noWhitespace();
$firstNameValidator = v::notEmpty();
$lastNameValidator = v::notEmpty();
$roleValidator = v::notEmpty();
$companyValidator = v::notEmpty();
$passwordValidator = v::length(8, null);
$validators = array('email' => $emailValidator, 'password' => $passwordValidator, 'first_name' => $firstNameValidator, 'last_name' => $lastNameValidator);
return new \DavidePastore\Slim\Validation\Validation($validators);
};
// route middleware
$container['homeRedirect'] = function ($container) {
$uri = $container->get('request')->getUri();
$identity = $container->get('authenticator')->getIdentity();
die(print_r($identity));
return true;
};
use Illuminate\Events\Dispatcher;
// route middleware
$container['events'] = function ($container) {
$event = new Dispatcher();
return $event;
示例15: date
$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
$slugfier = new \Slug\Slugifier();
$slugfier->setTransliterate(true);
$slug = $slugfier->slugify($name);
$password_secure = sha1($password);