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

前端登录表单为空点击直接提交跳转,如何添加空值校验触发报错?

解决方案

核心实现逻辑是在发起后端请求前新增前端表单字段校验,校验不通过时直接抛出前端错误、终止后续请求逻辑即可,具体修改如下:

  1. 调用axios.post前先对email、password做非空判断(额外做去空格处理,避免用户输入全空格绕过校验)
  2. 字段为空时直接调用setError设置对应提示,通过return终止后续代码执行
  3. 校验通过后再发起后端登录请求
    另外注意原代码存在笔误:axiox需要修正为axios,否则会触发依赖未定义报错。

修正后完整代码:

const login = (e) => {
    e.preventDefault();
    // 新增前端表单校验逻辑
    const trimmedEmail = email.trim()
    const trimmedPassword = password.trim()
    if (!trimmedEmail) {
        setError("请填写邮箱地址")
        return
    }
    if (!trimmedPassword) {
        setError("请填写登录密码")
        return
    }
    // 修正原代码笔误 axiox -> axios
    axios.post("http://localhost:2000/api/auth/login", {
        email: trimmedEmail,
        password: trimmedPassword
    }).then((response) => {
        console.log("response", response)
        localStorage.setItem("login", JSON.stringify({
            userLogin: true,
            token: response.data.access_token,
        }));
        setError("");
        setEmail("");
        setPassword("");
        history.push("schools");
    })
    .catch((error) => setError(error.response.data.message));
    
};

可选优化项

如果需要更严谨的校验,可以补充以下规则:

  • 邮箱格式合法性校验
const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
if (!emailReg.test(trimmedEmail)) {
    setError("请输入合法的邮箱格式")
    return
}
  • 密码长度校验
if (trimmedPassword.length < 6) {
    setError("密码长度不能少于6位")
    return
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 02:06:01