isFQDN.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import assertString from './util/assertString';
  2. import merge from './util/merge';
  3. var default_fqdn_options = {
  4. require_tld: true,
  5. allow_underscores: false,
  6. allow_trailing_dot: false,
  7. allow_numeric_tld: false,
  8. allow_wildcard: false,
  9. ignore_max_length: false
  10. };
  11. export default function isFQDN(str, options) {
  12. assertString(str);
  13. options = merge(options, default_fqdn_options);
  14. /* Remove the optional trailing dot before checking validity */
  15. if (options.allow_trailing_dot && str[str.length - 1] === '.') {
  16. str = str.substring(0, str.length - 1);
  17. }
  18. /* Remove the optional wildcard before checking validity */
  19. if (options.allow_wildcard === true && str.indexOf('*.') === 0) {
  20. str = str.substring(2);
  21. }
  22. var parts = str.split('.');
  23. var tld = parts[parts.length - 1];
  24. if (options.require_tld) {
  25. // disallow fqdns without tld
  26. if (parts.length < 2) {
  27. return false;
  28. }
  29. if (!options.allow_numeric_tld && !/^([a-z\u00A1-\u00A8\u00AA-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]{2,}|xn[a-z0-9-]{2,})$/i.test(tld)) {
  30. return false;
  31. } // disallow spaces
  32. if (/\s/.test(tld)) {
  33. return false;
  34. }
  35. } // reject numeric TLDs
  36. if (!options.allow_numeric_tld && /^\d+$/.test(tld)) {
  37. return false;
  38. }
  39. return parts.every(function (part) {
  40. if (part.length > 63 && !options.ignore_max_length) {
  41. return false;
  42. }
  43. if (!/^[a-z_\u00a1-\uffff0-9-]+$/i.test(part)) {
  44. return false;
  45. } // disallow full-width chars
  46. if (/[\uff01-\uff5e]/.test(part)) {
  47. return false;
  48. } // disallow parts starting or ending with hyphen
  49. if (/^-|-$/.test(part)) {
  50. return false;
  51. }
  52. if (!options.allow_underscores && /_/.test(part)) {
  53. return false;
  54. }
  55. return true;
  56. });
  57. }