Anmol Singh
Anmol Singh

Reputation: 661

Flutter: Either one of the 1st 2 conditions and either one of the 2nd 2 conditions, What's wrong with my code?

This is a validation for TextFormField(),

      if (value!.startsWith('http') ||
              value.startsWith('ftp') &&
          value.endsWith('jpg') || value.endsWith('png')) {
        return null;
      }
      return 'Check Again';
    },

Upvotes: 0

Views: 320

Answers (2)

Greed
Greed

Reputation: 46

According to operator instruction, && has higer precedence than ||. So your expression is equal to

if (...http || (...ftp && ...jpg) || ...png)`.

So the solution is

if ((...http || ...ftp) && (...jpg || ...png))

Upvotes: 2

Kishan Busa
Kishan Busa

Reputation: 911

You need to both your or (||) conditions into () because it will check all 4 conditions at the same time.

if ((value!.startsWith('http') || value.startsWith('fttp')) && (value.endsWith('jpg') || value.endsWith('png')))

By this, it will be divided into two groups. so now it will check first grouped conditions and then main conditions like

if ((true || true ) && (true || false))
if (true && true)

Upvotes: 0

Related Questions