Ruby on Rails NHS Number Validator

Following on from my JavaScript NHS Number validator, here it is converted to Ruby on Rails:

class NhsNumberValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)

    isValid = false

    if value.length == 10

        total = 0;
        i = 0;
        
        9.times {
            digit = value[i]
            factor = 10 - i
            total += (Integer(digit) * factor)
            i += 1
        }

        checkDigit = (11 - (total % 11))
        checkDigit = 0 if checkDigit == 11

        isValid = true if checkDigit == Integer(value[9])
    
    end

    record.errors[attribute] << "is not valid" unless isValid

  end
end

Javascript NHS Number validator

Here’s a JavaScript function that validates a UK NHS Number according to the rules set out in the NHS Data Dictionary using modulus 11. It’s pure JavaScript, but I wrote it to use in with some jQuery form validation.

function isValidNhsNumber(txtNhsNumber) {

    var isValid = false;

    if (txtNhsNumber.length == 10) {

        var total = 0;

        var i = 0;
        for (i = 0; i <= 8; i++) {
            var digit = txtNhsNumber.substr(i, 1);
            var factor = 10 - i;
            total += (digit * factor);
        }

        var checkDigit = (11 - (total % 11));
        
        if (checkDigit == 11) { checkDigit = 0; }

        if (checkDigit == txtNhsNumber.substr(9, 1)) { isValid = true; }
    }

    return isValid;
}

Note: it’s important to use txtNhsNumber.substr(9, 1) rather than txtNhsNumber.substr(-1) to get the check digit, as IE6 incorrectly returns the whole string rather than the last character if you use (-1).