formatCNICInput function

String formatCNICInput(
  1. String value
)

Formats a CNIC as the user types: 35202-1234567-1.

Keeps up to 13 digits (Urdu digits are converted) and inserts the dashes as the groups fill. Other characters are dropped.

Implementation

String formatCNICInput(String value) {
  final digits = _take(toAsciiDigits(value).replaceAll(_nonDigit, ''), 13);
  if (digits.length <= 5) return digits;
  if (digits.length <= 12) {
    return '${digits.substring(0, 5)}-${digits.substring(5)}';
  }
  return '${digits.substring(0, 5)}-${digits.substring(5, 12)}-'
      '${digits.substring(12)}';
}