2

I'm trying to create regex to validate all postal and zip codes format. I found an answer for this What is the ultimate postal code and zip regex? but it doesn't work in dart. Here are the criteria from the answer which are exactly what I'm looking for

  1. Every postal code system uses only A-Z and/or 0-9 and sometimes space/dash

  2. Not every country uses postal codes (ex. Ireland outside of Dublin), but we'll ignore that here.

  3. The shortest postal code format is Sierra Leone with NN

  4. The longest is American Samoa with NNNNN-NNNNNN

  5. You should allow one space or dash.

  6. Should not begin or end with space or dash

Here is the regex which I need to convert to dart (?i)^[a-z0-9][a-z0-9\- ]{0,10}[a-z0-9]$

delmin
  • 2,330
  • 5
  • 28
  • 54

2 Answers2

7
bool isZipValid = RegExp(r"^[a-z0-9][a-z0-9\- ]{0,10}[a-z0-9]$", caseSensitive: false).hasMatch(zip);

(?i) (case-insensitive mode) was the culprit for FormatException: Illegal RegExp pattern

Adelina
  • 10,915
  • 1
  • 38
  • 46
0

Format UK postcode

String _formattedPostcode(postcode) {
    RegExp regExp = RegExp(
      r'^([A-Z]{1,2}\d{1,2}[A-Z]?)\s*(\d[A-Z]{2})$'
    );
    var _pureString = postcode.replaceAll(' ', '');
    var fromat = regExp.hasMatch(_pureString);

    if(fromat) {
      final match = regExp.firstMatch(_pureString.toUpperCase());
      return "${match?.group(1)?.padLeft(2, '0')} ${match?.group(2)?.padLeft(2, '0')}";
    } else {
      return postcode;
    }
  }
Aathi
  • 2,599
  • 2
  • 19
  • 16