isFQDN.js 1.7 KB

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