Class LuhnValidator

  • All Implemented Interfaces:
    jakarta.validation.ConstraintValidator<Luhn,​CharSequence>

    public final class LuhnValidator
    extends ModulusValidator<Luhn>
    Modulus 10 Luhn Check Digit calculation/validation.

    Luhn check digits are used, for example, by:

    Check digit calculation is based on modulus 10 with digits in an odd position (from right to left) being weighted 1 and even position digits being weighted 2 (weighted values greater than 9 have 9 subtracted).

    See Wikipedia for more details.

    • Constructor Detail

      • LuhnValidator

        public LuhnValidator()
    • Method Detail

      • weightedValue

        protected int weightedValue​(int charValue,
                                    int leftPos,
                                    int rightPos)
                             throws Exception

        Calculates the weighted value of a charcter in the code at a specified position.

        For Luhn (from right to left) odd digits are weighted with a factor of one and even digits with a factor of two. Weighted values > 9, have 9 subtracted

        Calculates the weighted value of a character in the code at a specified position.

        Some modulus routines weight the value of a character depending on its position in the code (e.g. ISBN-10), while others use different weighting factors for odd/even positions (e.g. EAN or Luhn). Implement the appropriate mechanism required by overriding this method.

        Specified by:
        weightedValue in class ModulusValidator<Luhn>
        Parameters:
        charValue - The numeric value of the character
        leftPos - The position of the character in the code, counting from left to right
        rightPos - The position of the character in the code, counting from right to left
        Returns:
        The weighted value of the character
        Throws:
        Exception