validate method

  1. @override
String? validate({
  1. required String label,
  2. required String? value,
})
override

Ensures the value matches a properly formatted phone number. This supports both US and international phone number formats.

This will pass on empty or null values.

See also:

Implementation

@override
String? validate({
  required String label,
  required String? value,
}) {
  String? error;

  if (value?.isNotEmpty == true) {
    // Credit to this SO answer: https://stackoverflow.com/a/16702965
    const pattern =
        r'^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$';

    final regExp = RegExp(pattern);

    if (!regExp.hasMatch(value!)) {
      error = translate(
        FormValidationTranslations.form_validation_phone_number,
        {
          'label': label,
        },
      );
    }
  }

  return error;
}