DEV Community

loading...
Cover image for Day 13: Validate ISBN

Day 13: Validate ISBN

mattryanmtl profile image Matt Ryan ・1 min read

Check if the input is a valid ISBN (International Standard Book Number).

function checkIsbn(id) {
    var isbnRe = /\d-?\d{4}-?\d{4}-?[\dX]$/;
    if (!isbnRe.test(id))
        return false;

    var testId = id.split('-').join(''),
        result = 0;
    for (var i = 0; i < testId.length; i++)
    {
        var cur = testId[i] === 'X' ? 10 : parseInt(testId[i]);
        result += cur * (10 - i);
    }
    return (result % 11) === 0;
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

Forem Open with the Forem app