LuhnCheck and ignoreNonDigitCharacters


#1

I’m having an issue with the luhn check and want to know if I’m just using it wrong.
When I specify to ignoreNonDigitCharacters and have a trailing non-digit character, the last character (which is a non-digit) gets picked up as the check digit. Since it’s not a digit, the validation always fails.

The check for the ignoreNonDigitCharacters flag happens after getting the check digit.

I could find the last digit and send it in as the checkDigitIndex, but by that time, I might as well strip out non-digits myself.


#2

I checked the history and apparently it’s the desired behavior (see https://hibernate.atlassian.net/browse/HV-814).

I’ll check with Gunnar tomorrow to see if he has a recollection of the issue.


#3

Thanks for the response.

It makes sense that mod11 must use an “X” as a possible check digit (or whatever they specify), but that seems like an edge case.

I haven’t really thought this through, but perhaps something like each mod rule can define what it thinks is a “digit” or “check-digit”, then have ignoreNonDigitCharacters ignore whatever the mod rule thinks are digits.
The generic mod rule has [0-9] for both digits and checkDigits. mod11 could then specify that its checkdigits are [0-9X] (or 0-9 plus whatever the treat11as and treat10as are set to). The parsing of the field would be tricky (especially if you specified the start/end/checkDigit indexes).

Just a thought.
Thanks again for the answer.


#4

@kkalmbach could you give us examples of your input and what exactly you’re trying to do?

Might help us to find a suitable solution.


#5

Thanks for the help.
Here is a simple example… For this example, we could just strip out the trailing spaces (.trim()), but we could also have a trailing dash or anything else.

private static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
private static class SimpleLuhnCheck {
    @LuhnCheck
    String number;

    SimpleLuhnCheck(String c) {
        this.number =c;
    }
}

@Test
public void sampleTest() {
    SimpleLuhnCheck obj = new SimpleLuhnCheck("000000000000");
    Set<ConstraintViolation<SimpleLuhnCheck>> result = validator.validate(obj);
    assertEquals(0,result.size());
    obj = new SimpleLuhnCheck("0 0 0 0 0 0 0 0 0 0 0 0");
    result = validator.validate(obj);
    assertEquals(0,result.size());
    obj = new SimpleLuhnCheck("000000000000 ");
    result = validator.validate(obj);
    assertEquals(0,result.size());  // This line is currently failing

}