validateSecurityCode function
Validates the card's security code based allowed card type's length and whether it contains only numbers
Default length is 3 digits but American Express uses security codes that are 4 digits long
Implementation
ValidationResults validateSecurityCode(String code, CreditCardType type ) {
String trimmedCode = code.replaceAll(whiteSpaceRegex, '');
if (trimmedCode.isEmpty) {
return ValidationResults(
isValid: false,
isPotentiallyValid: false,
message: 'No security code given',
);
}
if (nonNumberRegex.hasMatch(trimmedCode)) {
return ValidationResults(
isValid: false,
isPotentiallyValid: false,
message: 'Alphabetic characters are not allowed',
);
}
// Set the correct security code length
int expectedCodeLength = type == CreditCardType.amex
? _ALT_SECURITY_CODE_LENGTH
: _DEFAULT_SECURITY_CODE_LENGTH;
if (trimmedCode.length < expectedCodeLength) {
return ValidationResults(
isValid: false,
isPotentiallyValid: true,
message: 'Security code is too short for this card type',
);
}
else if (trimmedCode.length > expectedCodeLength) {
return ValidationResults(
isValid: false,
isPotentiallyValid: false,
message: 'Security code is too long',
);
}
return ValidationResults(
isValid: true,
isPotentiallyValid: true,
);
}