validateMobile function

String validateMobile(
  1. String? mobile
)

Implementation

String validateMobile(String? mobile) {
  if (mobile == null || mobile.isEmpty) {
    return 'Mobile number is required';
  }

  String processedMobile = mobile;

  final nonDigitRegex = RegExp(r'[^0-9+]');
  if (nonDigitRegex.hasMatch(processedMobile)) {
    return 'Please enter a valid mobile number (digits only)';
  }

  if (processedMobile.startsWith('+91')) {
    processedMobile = processedMobile.substring(3);
  } else if (processedMobile.startsWith('91') && processedMobile.length > 10) {
    processedMobile = processedMobile.substring(2);
  } else if (processedMobile.startsWith('0')) {
    processedMobile = processedMobile.substring(1);
  }

  if (processedMobile.length != 10) {
    return 'Mobile number must be 10 digits (excluding country code)';
  }

  if (!RegExp(r'^[6-9]').hasMatch(processedMobile)) {
    return 'Mobile number must start with 6, 7, 8, or 9';
  }

  return '';
}