isISBN function

  1. @experimental
bool isISBN(
  1. String? str, [
  2. String? version
])

Returns true if str is a valid ISBN-10 or ISBN-13.

Pass version as '10' or '13' to check a specific standard. Returns false if str is null.

Implementation

@experimental
bool isISBN(String? str, [String? version]) {
  if (str == null) return false;
  if (version == null) return isISBN(str, '10') || isISBN(str, '13');

  final sanitized = str.replaceAll(RegExp(r'[\s-]+'), '');
  var checksum = 0;

  if (version == '10') {
    if (!isbn10MaybeReg.hasMatch(sanitized)) return false;
    for (var i = 0; i < 9; i++) {
      checksum += (i + 1) * int.parse(sanitized[i]);
    }
    checksum += sanitized[9] == 'X' ? 100 : 10 * int.parse(sanitized[9]);
    return checksum % 11 == 0;
  } else if (version == '13') {
    if (!isbn13MaybeReg.hasMatch(sanitized)) return false;
    const factor = [1, 3];
    for (var i = 0; i < 12; i++) {
      checksum += factor[i % 2] * int.parse(sanitized[i]);
    }
    return int.parse(sanitized[12]) - ((10 - (checksum % 10)) % 10) == 0;
  }

  return false;
}