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

如何在Django中满足条件时创建并显示验证提示消息?

表单验证提示消息实现方案

需求说明

开发认证Web应用,当用户输入不符合条件时显示对应提示消息,例如:密码长度小于8位时,显示Password should be longer than 8 characters!。

步骤1:修改视图代码

优化原视图逻辑,添加错误提示消息到context:

def signup(request):
    if request.method == "POST":
        context = {
            'has_error': False,
            'data': request.POST,
            # 新增错误提示消息字段
            'length_error_msg': '',
            'password_match_error_msg': '',
            'validate_email_error_msg': '',
            'username_error_msg': '',
            'email_exists_error_msg': ''
        }
        # 使用局部变量替代全局变量
        email = request.POST.get('email')
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')

        if len(password) < 8:
            context['length_error_msg'] = 'Password should be longer than 8 characters!'
            context['has_error'] = True

        if password != password2:
            context['password_match_error_msg'] = 'Passwords do not match!'
            context['has_error'] = True

        if not validate_email(email):
            context['validate_email_error_msg'] = 'Please enter a valid email address!'
            context['has_error'] = True

        if not username:
            context['username_error_msg'] = 'Username cannot be empty!'
            context['has_error'] = True

        if models.CustomUser.objects.filter(email=email).exists():
            context['email_exists_error_msg'] = 'This email is already registered!'
            context['has_error'] = True

        # 所有错误检查完成后统一返回模板,避免提前返回跳过其他验证
        if context['has_error']:
            return render(request, 'authentication/signup.html', context, status=400)

        # 邮件发送逻辑(需确保token变量已正确生成)
        body = render_to_string('authentication/email/email_body.html', {
            'username': username,
            'token': token,
        })
        send_mail(
            "Email Confirmation",
            body,
            'tadejtilinger@gmail.com',
            [email]
        )
        return redirect('email-confirmation')
    return render(request, 'authentication/signup.html')

步骤2:修改signup.html模板

在每个输入框下方添加错误提示元素,通过模板判断显示对应消息:

{% include "_base.html" %}
{% load static %}

{% block title %}Sign Up{% endblock title %}

{% block content %}
<link rel="stylesheet" href="{% static 'css/authentication/signup.css' %}">
<div class="container">
  <form class="signup_form" method="post" action="{% url 'signup' %}">
    {% csrf_token %}
    <!-- 邮箱输入区域 -->
    <input type="email" placeholder="Email" class="input_1" name="email" value="{{ data.email }}">
    {% if email_exists_error_msg or validate_email_error_msg %}
        <div class="error-message">{{ email_exists_error_msg }}{{ validate_email_error_msg }}</div>
    {% endif %}

    <!-- 用户名输入区域 -->
    <input type="text" placeholder="Username" class="input_2" name="username" value="{{ data.username }}">
    {% if username_error_msg %}
        <div class="error-message">{{ username_error_msg }}</div>
    {% endif %}

    <!-- 密码输入区域 -->
    <input type="password" placeholder="Password" class="input_3" name="password" value="{{ data.password }}">
    {% if length_error_msg %}
        <div class="error-message">{{ length_error_msg }}</div>
    {% endif %}

    <!-- 确认密码输入区域 -->
    <input type="password" placeholder="Confirm password" class="input_4" name="password2" value="{{ data.password2 }}">
    {% if password_match_error_msg %}
        <div class="error-message">{{ password_match_error_msg }}</div>
    {% endif %}

    <button type="submit" class="submit_btn1">Sign Up</button>
  </form>
</div>
{% block scripts %}
<script src="{% static 'js/signup.js' %}"></script>
{% endblock scripts %}
{% endblock content %}

注意:将密码输入框的type从text改为password,符合账号安全规范。

步骤3:添加样式美化提示消息

在signup.css中添加错误提示的样式:

.error-message {
    color: #dc3545;
    font-size: 0.875rem;
    margin-top: 0.25rem;
    margin-bottom: 0.75rem;
}

.signup_form input {
    display: block;
    width: 100%;
    margin-bottom: 0.5rem;
    padding: 0.5rem;
    box-sizing: border-box;
}

可选:前端实时验证补充

如果需要在用户输入时实时提示,可以在signup.js中添加前端验证逻辑:

document.addEventListener('DOMContentLoaded', function() {
    const passwordInput = document.querySelector('input[name="password"]');
    const confirmPasswordInput = document.querySelector('input[name="password2"]');

    // 密码长度实时验证
    passwordInput.addEventListener('blur', function() {
        const errorEl = this.nextElementSibling;
        if (this.value.length < 8) {
            errorEl.textContent = 'Password should be longer than 8 characters!';
            errorEl.style.display = 'block';
        } else {
            errorEl.style.display = 'none';
        }
    });

    // 确认密码匹配实时验证
    confirmPasswordInput.addEventListener('blur', function() {
        const errorEl = this.nextElementSibling;
        if (this.value !== passwordInput.value) {
            errorEl.textContent = 'Passwords do not match!';
            errorEl.style.display = 'block';
        } else {
            errorEl.style.display = 'none';
        }
    });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 12:36:16