isbn.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. define("dojox/validate/isbn", ["dojo/_base/lang", "./_base"], function(lang, validate){
  2. // summary: Provides ISBN validation functions in `dojox.validate`
  3. //
  4. /*=====
  5. validate = dojox.validate;
  6. =====*/
  7. validate.isValidIsbn = function(/* String */value) {
  8. // summary: Validate ISBN-10 or ISBN-13 based on the length of value
  9. // value: String
  10. // An ISBN to validate
  11. // returns: Boolean
  12. var len, sum = 0, weight;
  13. if(!lang.isString(value)){
  14. value = String(value);
  15. }
  16. value = value.replace(/[- ]/g,''); //ignore dashes and whitespaces
  17. len = value.length;
  18. switch(len){
  19. case 10:
  20. weight = len;
  21. // ISBN-10 validation algorithm
  22. for(var i = 0; i < 9; i++){
  23. sum += parseInt(value.charAt(i)) * weight;
  24. weight--;
  25. }
  26. var t = value.charAt(9).toUpperCase();
  27. sum += t == 'X' ? 10 : parseInt(t);
  28. return sum % 11 == 0; // Boolean
  29. break;
  30. case 13:
  31. weight = -1;
  32. for(var i = 0; i< len; i++){
  33. sum += parseInt(value.charAt(i)) * (2 + weight);
  34. weight *= -1;
  35. }
  36. return sum % 10 == 0; // Boolean
  37. break;
  38. }
  39. return false;
  40. };
  41. return validate.isValidIsbn;
  42. });