简体   繁体   中英

Laravel regex validation for empty string

I have the following validation,
it should match string with letters,numbers,dashes. And empty input should also be valid.
The normal string validation is ok, but I can not make it match "empty" input.

'letter_code' => 'regex:/^[A-Za-z0-9\-]*$/'

letter_code format is invalid

tests :
"C14" // valid
"3.14" // "format is invalid", as expected
"-" // valid
"" // "format is invalid", NOT expected

I just found out in laracasts forum , that there is a nullable rule.
You can read about it in the official docs .

Without the nullable rule empty strings are considered invalid if there is a regex rule as well.

If you don't add required as additional validator empty string must pass

Here is phpunit test:

/** @test */
public function letterCode()
{
    $trans = new \Illuminate\Translation\Translator(
        new \Illuminate\Translation\ArrayLoader, 'en'
    );

    $regex = 'regex:/^[A-Za-z0-9\-]*$/';

    $v = new Validator($trans, ['x' => 'C14'], ['x' => $regex]);
    $this->assertTrue($v->passes());

    $v = new Validator($trans, ['x' => '3.14'], ['x' => $regex]);
    $this->assertFalse($v->passes());

    $v = new Validator($trans, ['x' => '-'], ['x' => $regex]);
    $this->assertTrue($v->passes());

    $v = new Validator($trans, ['x' => ''], ['x' => $regex]);
    $this->assertTrue($v->passes());
}

This is tested with Laravel 5.5

I was facing the same problem in Laravel 7.x using GraphQL Types . I needed something similar to this in a field called phone or nothig (empty string). So I did something like this:

'phone' => [
        'name' => 'phone',
        'type' => Type::string(),
        'rules' => ['regex:/^[A-Za-z0-9\-]*$/','nullable']

Here, phone is the name of the field you want to enter text into, and rules is what we define as regex, or NULL.

Hope this helps someone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM