John Davidson

Insert variable in validator (PHP)

0 comments
Message:


I got the following validator:


#[NexusAssert\HasZeroOrXAmountOfCharacters]


With the following constraint:



/**
* @Annotation
*/
#[Attribute]
class HasZeroOrXAmountOfCharacters extends Constraint
{
public string $message = 'Wrong number of characters';

public function validatedBy(): string
{
return static::class . 'Validator';
}

}

And the following validator function:


public function validate($value, Constraint $constraint)
{
$values = explode(",",$value);
$count = count($values);


if ((1 < $count) && ($count < 13) ) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ string }}', $value)
->addViolation();
}

}

I would like to give a variable to the NexusAssert like:


#[NexusAssert\HasZeroOrXAmountOfCharacters(charAmount = 13)]


And put 'charAmount' in the validate function, instead of a hard coded number. I'd like to know if and how this is possible.



My Answer:
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users,email',
'password' => 'required|string|min:6',
]);

Rate this post

3 of 5 based on 9611 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us