isFQDN.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. }
  32. // disallow spaces
  33. if (/\s/.test(tld)) {
  34. return false;
  35. }
  36. }
  37. // reject numeric TLDs
  38. if (!options.allow_numeric_tld && /^\d+$/.test(tld)) {
  39. return false;
  40. }
  41. return parts.every(function (part) {
  42. if (part.length > 63 && !options.ignore_max_length) {
  43. return false;
  44. }
  45. if (!/^[a-z_\u00a1-\uffff0-9-]+$/i.test(part)) {
  46. return false;
  47. }
  48. // disallow full-width chars
  49. if (/[\uff01-\uff5e]/.test(part)) {
  50. return false;
  51. }
  52. // disallow parts starting or ending with hyphen
  53. if (/^-|-$/.test(part)) {
  54. return false;
  55. }
  56. if (!options.allow_underscores && /_/.test(part)) {
  57. return false;
  58. }
  59. return true;
  60. });
  61. }