3

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

8
  • Show your test cases Commented Oct 15, 2017 at 13:42
  • 1
    @Marcin The test case is the empty string, I guess. Commented Oct 15, 2017 at 13:42
  • Is this in a validator? What exactly are you trying to do? Do you want to allow and empty string or make sure it’s not empty? Commented Oct 15, 2017 at 13:44
  • 1
    I mean the code. Regexp looks fine for me Commented Oct 15, 2017 at 13:45
  • does 'letter_code' => 'regex:/^[A-Za-z0-9\-]*$/|min:0' work? Commented Oct 15, 2017 at 13:48

3 Answers 3

11

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is actually the correct answer as compared to the one with more up votes at this time.
To add to this: in Laravel the ConvertEmptyStringsToNull middleware parses empty strings to null. Without the nullable rule, nulls are considered invalid.
2

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

Comments

1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.