Rule #1 — ISBN Numbers

While you might think that writing the logic involved for validating an ISBN number is simple, you’d be wrong. Part of this stems from ISBN existing in two formats 10 and 13, but it’s also the case that you can display it in a range of ways (with or without spaces, with or without the ISBN prefix etc.)

If you’re interested in learning more about the complexity of validating ISBN numbers, check out this article on the O’Reilly website.

NOTE: Technically, it is possible for the number to be valid, but the final character to be invalid if the checksum is wrong. If this is of concern to you, you can always implement a PHP version of the solution shown via the link above.

Needless to say, the quickest approach is to use a regular expression to see if an ISBN is likely to be valid, so let’s insert that logic into the passes method:

public function passes($attribute, $value)

{

return preg_match(

"/^(?:ISBN(-1(?:(0)|3))?:?\ )?(?(1)(?(2)(?=[0-9X]{10}$|(?=

(?:[0-9]+[- ]){3})[- 0-9X]{13}$)[0-9]{1,5}[- ]?[0-9]+[- ]?

[0-9]+[- ]?[0-9X]|(?=[0-9]{13}$|(?=(?:[0-9]+[- ]){4})[- 0-

9]{17}$)97[89][- ]?[0-9]{1,5}[- ]?[0-9]+[- ]?[0-9]+[- ]?[0-

9])|(?=[0-9X]{10}$|(?=(?:[0-9]+[- ]){3})[- 0-9X]

{13}$|97[89][0-9]{10}$|(?=(?:[0-9]+[- ]){4})[- 0-9]{17}$)

(?:97[89][- ]?)?[0-9]{1,5}[- ]?[0-9]+[- ]?[0-9]+[- ]?[0-

9X])$/", $value

);

}

Next, we’ll need to write an error message to respond with when the user has supplied a value which is not a valid ISBN number:

public function message()

{

return 'The :attribute must be a valid ISBN number';

}

As before, we’ll write a quick unit test to confirm that the rule works correctly and rejects values that are not ISBN numbers: