简体   繁体   中英

Laravel 9 Validation: Why am I getting 'Array to string conversion' error when I pass value in lower case?

I have an API input as follows:

a. company_name
b. county 
c. state 

I have entered below values for the same:

a. company_name:Some Name
c. country:in
d. state:MH

Below is my validation rule:

$rule = [
     'company_name' => ['required'],
     'country' => ['required', 'string', 'regex:/^[A-Z]{2}+$/','exists:table_name,column_name'],
     'state' => ['required','regex:/^[A-Z]{2}+$/'],    
];

The Issue:
But on testing I encountered a strange issue where if I pass the 'country' value in upper case which is intended, it works fine because in table it is in uppercase only. But if I pass it in lowercase, in which I am expecting to get validation error with help of regex, there it gives me:

ErrorException: Array to string conversion

Debugging:

  1. This happens as soon as the lowercase value is passed to the 'exists:table_name,column_name' , else there's no problem if I comment it out.
  2. I checked lowercase string is getting passed to the table attribute.
  3. String keyword is mentioned in the laravel validation part against the field.

Question:

  1. It should have thrown validation of lowercase regex before moving ahead with the table lookup, right?
  2. What to do if I want to validate in that way? So what could be issue?

My expected output:
Getting validation error of the mentioned field to be in uppercase like this:

{
    "status": false,
    "status_code": 400,
    "message": "Request validation error.",
    "validation": {
        "country": [
            [
                "Country should be in captial alphabetic letters of 2 characters in length."
            ]
        ]
    }
}

Thanks in advance.

Laravel has built in uppercase rule. It will return an error in cases where any character is lowercase.

Assuming you want to check countries on 2 letter for example like UK I suggest installing a libary like League\ISO3166 then make a custom validation rule that looks something like this

public function passes($attribute, $value): bool
{
    if (! is_string($value)) {
        return false;
    }

    $iso3166 = new ISO3166();

    try {
        $iso3166->alpha2($value);

        return true;
    } catch (DomainException|OutOfBoundsException $exception) { 
        return false;
    }

return false;
}

This libary also check for u if the country tag is this case is a valid ISO3166 meaning for example NL passes but EP is non existing country so it will fail

I know this is not a regex solution but this prob will even work better in this use case

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