How do I validate an Australian Medicare number?

Viewed 24504

I'm developing an online form in which user-entered Medicare numbers will need to be validated.

(My specific problem concerns Australian Medicare numbers, but I'm happy for answers regarding American ones too. This question is about Medicare numbers in general.)

So how should I do it?

(It would be good to have the answer in Javascript or a regex.)

14 Answers

Here's a Typescript or modern Javascript solution:

  validateMedicare(medicare) {
    let isValid = false;

    if (medicare && medicare.length === 10) {
      const matches = medicare.match(/^(\d{8})(\d)/);

      if (!matches) {
        return { invalid: true };
      }

      const base = matches[1];
      const checkDigit = matches[2];
      const weights = [1, 3, 7, 9, 1, 3, 7, 9];

      let sum = 0;
      for (let i = 0; i < weights.length; i++) {
        sum += parseInt(base[i], 10) * weights[i];
      }

      isValid = sum % 10 === parseInt(checkDigit, 10);
    }

    return isValid;
  }

Please refer to http://clearwater.com.au/code/medicare for an explanation.

To test, generate medicare number here: https://precedencehealthcare.com/rmig/

Added Dart version:

bool isMedicareValid(String input, {bool validateWithIrn = true}) {
  final medicareNumber = input.replaceAll(" ", "");
  final length = validateWithIrn ? 11 : 10;

  if (medicareNumber.length != length) {
    return false;
  }

  final multipliers = [1, 3, 7, 9, 1, 3, 7, 9];
  final regexp = RegExp("^(\\d{8})(\\d)", caseSensitive: false);

  final matches = regexp.allMatches(medicareNumber).toList();

  if (matches.length > 0 && matches[0].groupCount >= 2) {
    final base = matches[0].group(1);
    final checkDigit = matches[0].group(2);
    var total = Iterable.generate(multipliers.length)
        .fold(0, (current, index) => current += (int.tryParse(base[index]) * multipliers[index]));

    return (total % 10) == int.parse(checkDigit);
  }
  return false;
}

Another Swift implementation with comments:

func validateMedicareNumber(input: String) -> Bool {
    let weights = [1, 3, 7, 9, 1, 3, 7, 9]

    // Remove all whitespace
    var trimmed = input.trimmingCharacters(in: .whitespacesAndNewlines)
        .components(separatedBy: .whitespaces)
        .joined()

    // The medicare card number has 8 digits identifier + 1 digit checksum + 1 digit issue number.
    // Either 9 or 10 numbers will be valid
    guard trimmed.count == 9 || trimmed.count == 10 else {
        return false
    }

    // Drop the issue number if it was added
    if trimmed.count == 10 {
        trimmed = String(trimmed.dropLast())
    }

    // The last digit is a checksum
    guard let lastElement = trimmed.last,
        let checkSum = Int(String(lastElement)) else {
        return false
    }

    // Remove the checksum from our input
    trimmed = String(trimmed.dropLast())

    // Multiply the numbers by weights
    let weightedNumbers: [Int] = trimmed.enumerated().map { index, element in
        guard let number = Int(String(element)) else {
            // -1 will throw the calculations out of the window which
            // will guarantee invalid checksum
            return -1
        }

        return number * weights[index]
    }

    // Validate the weighted numbers against the checksum
    return weightedNumbers.reduce(0, +) % 10 == checkSum
}

If you need a test card number for development, use this one. It's for John Doe

TEST CARD NUMBER > 2428 77813 2/1

Expanding on Daniel Ormeño answer, for asp.net you can put the check into an attribute and decorate the property in the model

public class MedicareValidation : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        string medicareNumber = value.ToString();

        if (!(medicareNumber?.Length >= 10 && medicareNumber.Length < 12) || !medicareNumber.All(char.IsDigit))
            return false;

        var digits = medicareNumber.Select(c => (int)char.GetNumericValue(c)).ToArray();
        return digits[8] == GetMedicareChecksum(digits.Take(8).ToArray());
    }

    private int GetMedicareChecksum(int[] digits)
    {
        return digits.Zip(new[] { 1, 3, 7, 9, 1, 3, 7, 9 }, (m, d) => m * d).Sum() % 10;
    }
}

Then in the model

[DisplayName("Medicare Number")]  
[MedicareValidation] 
public string MedicareNumber {get; set;}

Here's a Python version! Note that it expects a full 11 digit Medicare number. If you're validating 10 digit Medicare numbers without the individual reference number, you'll need to tweak the regex in the re.match line.

def validate_medicare_number(medicare_number: str) -> bool:
    """Given a string containing a medicare number, return True if valid,
    False if invalid.

    >>> validate_medicare_number("2428 77813 2/1")
    True
    >>> validate_medicare_number("7428 77818 2/1")
    False
    >>> validate_medicare_number("2428 77815 2/1")
    False
    """

    # See here for checksum algorithm:
    # https://stackoverflow.com/a/15823818
    # https://clearwater.com.au/code/medicare

    # Remove whitespace
    medicare_number = re.sub(r"[^\d]+", "", medicare_number)
    if re.match(r"^[2-6]\d{10}$", medicare_number):

        medicare_digits = list(map(int, medicare_number))
        checksum_weights = (1, 3, 7, 9) * 2
        digit_weight_pairs = zip(medicare_digits, checksum_weights)
        checksum = sum([digit * weight for digit, weight in digit_weight_pairs]) % 10

        return checksum == medicare_digits[8]
    else:
        return False

You can use simple regex validation: .replace(/\W/gi, "") .replace(/(.{4})(.{5})/g, "$1 $2 ");

check my example here: codesandbox.io

Related