You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React表单中验证用户是否输入了合法域名

纯域名输入校验的简便实现方案

下面分两种常用的轻量实现,不需要引入第三方依赖:

方案1:利用URL构造器实现无正则校验

这个方案不需要维护复杂正则规则,适配所有符合URL规范的合法域名,也能自动兼容用户不小心输入http:///https://前缀的场景:
核心校验函数代码:

const isValidDomain = (input) => {
  // 先去除前后空格和可能自带的http/https前缀
  const trimmedInput = input.trim().replace(/^https?:\/\//, '');
  try {
    const testUrl = new URL(`http://${trimmedInput}`);
    // 校验host等于输入内容,避免用户输入带路径、参数的非法内容
    return testUrl.host === trimmedInput;
  } catch (err) {
    return false;
  }
}

React组件中使用示例:

import { useState } from 'react';

const DomainInput = () => {
  const [domain, setDomain] = useState('');
  const [errorTip, setErrorTip] = useState('');

  const validateDomain = () => {
    if (!domain.trim()) return;
    if (!isValidDomain(domain)) {
      setErrorTip('请输入合法域名,示例:company.com');
      return;
    }
    setErrorTip('');
    // 校验通过后的业务逻辑
  };

  return (
    <div className="domain-input-wrap">
      <input
        type="text"
        value={domain}
        onChange={(e) => setDomain(e.target.value)}
        onBlur={validateDomain}
        placeholder="请输入公司域名"
      />
      {errorTip && <span className="error">{errorTip}</span>}
    </div>
  );
};

方案2:正则校验

如果偏好正则实现,可使用通用性较高的域名校验规则,性能更优:

const domainRegex = /^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$/;

// 校验调用
const isValid = domainRegex.test(userInput.trim());

注意事项

  • 若业务允许输入带端口的域名,可调整URL校验逻辑保留host中的端口部分,或调整正则匹配规则
  • 校验通过后可统一格式化输出内容,比如自动去除多余的协议前缀、前后空格,保证存储的域名格式统一
  • 若需要避免用户输入不存在的伪顶级域名,可自行维护常用顶级域名列表做二次校验

内容的提问来源于stack exchange,提问作者james wisley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 14:06:05