skip to Main Content

I need to validate a string whose length is exactly 6 OR 8. How could I make the rule for this validation?

The number must be 6 OR 8, it cannot be between 6 and 8.

3

Answers


  1. You need to create a custom rule.

    In the sample below, I used the Closure to create a custom rule, but you can create a rule object to reuse it.

    I used the mb_strlen instead of strlen to cover multibyte. (UTF8 chars)

    use IlluminateSupportFacadesValidator;
    use IlluminateHttpRequest;
    
    Route::get('/test', function (Request $request) {
        $validator = Validator::make($request->all(), [
            'title' => [
                'required',
                function ($attribute, $value, $fail) {
                    if (!(mb_strlen($value) == 8 || mb_strlen($value) == 6))
                    {
                        $fail('The ' . $attribute . ' is invalid.');
                    }
                },
            ],
        ]);
    
        dd($validator->errors());
    });
    
    Login or Signup to reply.
  2. Try saving string length first and then check with if conditions.

    $str = “hellowld”;
    $len = strlen($str);
    If($len == 6 || $len == 8)
        //do something 
    Else
        //throw error
    

    or use regex validation rule for length as:

     /^[68]+$/
    

    For string length.

    Login or Signup to reply.
  3. You don’t actually need to make your own validator, since Laravel’s validation comes with a regex validation rule, so you could just do:

    [
        ...
        'parameter' => 'regex:/^(.{6}|.{8})$/g',
        ...
    ]
    

    Regex stolen and adapted from here but you can test it here

    Regex Explanation:

    ^    # Start of string
    (    # Start capture group
    .    # Matches any character except line breaks
    {6}  # Quantifier that only matches 6 preceding tokens (.)
    |    # OR operator
    .    # Matches any character except line breaks
    {8}  # Quantifier that only matches 8 preceding tokens (.)
    )    # End capture group
    $    # End of string
    

    OLD ANSWER (unnecessarily complicated)

    [
        ...
        'parameter' => 'regex:/^(?=.*$)(?:.{6}|.{8})$/g',
        ...
    ]
    

    Regex Explanation:

    ^    # Start of string
    (?=  # Start of positive lookahead
    .*   # Matches any character except line breaks 0 or more times
    $    # End of string
    )    # End of positive lookahead
    (?:  # Start of non-capturing group
    .{6} # Matches any character except line breaks exactly 6 times
    |    # OR operator
    .{8} # Matches any character except line breaks exactly 8 times
    )    # End non-capturing group
    $    # End of string
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search