Skip to content

Instantly share code, notes, and snippets.

@outrowender
Created November 12, 2021 20:34
Show Gist options
  • Save outrowender/b7af55ab1705c67f54bc6ae517673bb1 to your computer and use it in GitHub Desktop.
Save outrowender/b7af55ab1705c67f54bc6ae517673bb1 to your computer and use it in GitHub Desktop.
dart Phone number validation with regex
class Phone {
final String _areacode;
final String _specialDigit;
final String _localPhone;
Phone._(this._areacode, this._specialDigit, this._localPhone);
static Phone? create(String? candidate) {
final candidateFormatted = candidate!.replaceAll(RegExp('[^0-9]'), '');
//https://regex101.com/r/P85Luy/1
final regExp = RegExp(r'^(55)?(0?\d{2})(9)?(\d{8})$');
final tokens = regExp.allMatches(candidateFormatted);
if (tokens.isEmpty) return null;
tokenAt(int index) => tokens.elementAt(0).group(index) ?? '';
return Phone._(tokenAt(2), tokenAt(3), tokenAt(4));
}
String get formatted {
return '$_areacode$_specialDigit$_localPhone';
}
bool get isCellPhone {
return _specialDigit.isNotEmpty;
}
}
import 'package:flutter_test/flutter_test.dart';
import 'phone.dart';
void main() {
group('Phone number tests', () {
test('valid phone number -> should be a Phone instance', () {
const value = '011 9 5559 7125';
final phone = Phone.create(value);
expect(phone, isNotNull);
});
test('mobile phone without area code -> should be invalid', () {
const value = '9 5559 7125';
final phone = Phone.create(value);
expect(phone, isNull);
});
test('number without country code -> should return a valid full mobile number', () {
const value = '011 9 5559 7125';
final phone = Phone.create(value);
expect(phone!.formatted, '011955597125');
});
test('number without country code -> when receive a custom country code -> should return a valid full mobile number', () {
const value = '011 9 5559 7125';
final phone = Phone.create(value);
expect(phone!.formatted, '011955597125');
});
test('number with country code -> should return a valid full mobile number', () {
const value = '+55 011 9 5559 7125';
final phone = Phone.create(value);
expect(phone!.formatted, '011955597125');
});
test('number without special digit -> should be a phone', () {
const value = '011 5559 7125';
final phone = Phone.create(value);
expect(phone!.isCellPhone, isFalse);
});
test('number with special digit -> should be a mobile phone', () {
const value = '011 9 5559 7125';
final phone = Phone.create(value);
expect(phone!.isCellPhone, isTrue);
});
test('number without special digit -> when formatted -> should be a full phone number', () {
const value = '011 5559 7125';
final phone = Phone.create(value);
expect(phone!.formatted, '01155597125');
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment