gpt4 book ai didi

python - 使用 AJAX 时 wtforms 验证不起作用

转载 作者:行者123 更新时间:2023-12-04 10:28:33 28 4
gpt4 key购买 nike

我的页面上有 2 个表格 - 登录表格和注册表单。现在我想使用 AJAX 来验证这些表单,这样我就可以在不刷新页面的情况下查看输入错误。我试图将所有 AJAX 内容添加到我已有的表单中,但现在表单验证似乎不起作用。

路线.py

@users.route('/login', methods=['GET', 'POST'])
def login():
loginForm = LoginForm()
registerForm = RegisterForm()

if request.method == 'POST':
if registerForm.validate():
return'wow it works'
return 'something is wrong'

return render_template("login.html", loginForm=loginForm, registerForm=registerForm)

附言我还想知道在发送 POST 请求时如何检查要验证的表单?现在我只是想弄清楚如何解决这个问题,所以我只使用注册表。但是,当我同时拥有如何验证一种形式并忽略另一种形式时?

login.html

const signUpButton = document.getElementById("signUp");
const signInButton = document.getElementById("signIn");
const container = document.getElementById("container");

signUpButton.addEventListener('click', () => {
container.classList.add("right-panel-active");
});

signInButton.addEventListener('click', () => {
container.classList.remove("right-panel-active");
});



const fields = {
username: {
input: document.getElementById('username'),
error: document.getElementById('username-error')
},

email: {
input: document.getElementById('email'),
error: document.getElementById('email-error')
},

password: {
input: document.getElementById('password'),
error: document.getElementById('password-error')
},

confirm_password: {
input: document.getElementById('confirm_password'),
error: document.getElementById('confirm-password-error')
}

}

var regForm = document.getElementById('register-form');
regForm.addEventListener('submit', async (e) => {
e.preventDefault();

const response = await fetch('/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},

body: JSON.stringify({
username: fields.username.input.value,
email: fields.email.input.value,
password: fields.password.input.value,
confirm_password: fields.confirm_password.input.value
})
});

if (response.ok) {
alert('yes');
console.log(response);
}
else {
const errors = await response.json();
Object.key(errors).forEach((key) => {
fields[key].input.classList.add('input-invalid');
fields[key].error.innerHTML = errors[key][0];
});
}
});
<div class="form-container sign-up-container">
<form id="register-form" action="" method="POST">
{{ registerForm.hidden_tag() }}

<h1>Create an account</h1>

<fieldset class="uk-fieldset">
<div class="uk-margin form-group">
{% if registerForm.username.errors %} {{ registerForm.username(class="uk-input input-invalid") }}

<div class="input-erros" id="username-error">
{% for error in registerForm.username.errors %}
<span>{{ error }}</span> {% endfor %}
</div>

{% else %} {{ registerForm.username(class="uk-input") }} {% endif %}
</div>

<div class="uk-margin form-group" id="email-error">
{% if registerForm.email.errors %} {{ registerForm.email(class="uk-input input-invalid") }}

<div class="input-erros">
{% for error in registerForm.email.errors %}
<span>{{ error }}</span> {% endfor %}
</div>

{% else %} {{ registerForm.email(class="uk-input") }} {% endif %}
</div>

<div class="uk-margin form-group" id="password-error">
{% if registerForm.password.errors %} {{ registerForm.password(class="uk-input input-invalid") }}

<div class="input-erros">
{% for error in registerForm.password.errors %}
<span>{{ error }}</span> {% endfor %}
</div>

{% else %} {{ registerForm.password(class="uk-input") }} {% endif %}
</div>

<div class="uk-margin form-group" id="confirm-password-error">
{% if registerForm.confirm_password.errors %} {{ registerForm.confirm_password(class="uk-input input-invalid") }}

<div class="input-errors">
{% for error in registerForm.confirm_password.errors %}
<span>{{ error }}</span> {% endfor %}
</div>

{% else %} {{ registerForm.confirm_password(class="uk-input") }} {% endif %}
</div>

<div class="uk-margin form-group">

</div>
</fieldset>

<button class="form-button">Create an account</button>
</form>
</div>


<div class="form-container sign-in-container">
<form action="#">
<h1>Sign In</h1>

<fieldset class="uk-fieldset">
<div class="uk-margin">
{{ loginForm.usernameLogin(class="uk-input") }}
</div>

<div class="uk-margin">
{{ loginForm.passwordLogin(class="uk-input") }}
</div>

<div class="uk-margin">
{{ loginForm.submit(class="form-button") }}
</div>
</fieldset>
</form>
</div>


<div class="overlay-container">
<div class="overlay">

<div class="overlay-panel overlay-left">
<h1>Don't have an account yet?</h1>
<!-- <p>just sign in</p> -->
<button class="ghost form-button" id="signUp">Create an account</button>
</div>

<div class="overlay-panel overlay-right">
<h1>Already have an account?</h1>
<!-- <p>become a part of the community</p> -->
<button class="ghost form-button" id="signIn">Sign In</button>
</div>

</div>
</div>


forms.py
class RegisterForm(FlaskForm):
username = StringField('username',
validators=[
DataRequired("username is required"),
Length(min=5,
max=15,
message="must be between 5 and 15 characters")
],
render_kw={"placeholder": "username"})

email = StringField('e-mail',
validators=[
DataRequired("e-mail is required"),
Email(message="probably not e-mail")
],
render_kw={"placeholder": "e-mail"})

password = PasswordField('password',
validators=[DataRequired("password is required")],
render_kw={"placeholder": "password"})

confirm_password = PasswordField('confirm password',
validators=[
DataRequired("confirm password"),
EqualTo('password')
],
render_kw={"placeholder": "confirm password"})


def validate_username(self, username):
pass

def validate_email(self, email):
pass

def validate_password(self, password):
pswd = password.data
flag = 0

while True:
if (len(pswd)<8):
flag = -1
break

elif not re.search("[a-z]", pswd):
flag = -1
break

elif not re.search("[A-Z]", pswd):
flag = -1
break

elif not re.search("[0-9]", pswd):
flag = -1
break

else:
flag = 0
break

if flag == -1:
raise ValidationError('the password is too simple')

当我提交注册表时,似乎只有 DataRequired 验证器有效。因为我可以在电子邮件和密码中输入任何内容,而且我仍然收到"is"警报,就像回复没问题一样。

最佳答案

使用 WTForms 验证 JSON 请求与处理普通的 urlencoded 表单请求略有不同。

这是使用 RegisterForm 的简单示例从问题。

# imports here
...
import wtforms_json

# Initialise wtforms_json
wtforms_json.init()

app = Flask(__name__)
app.config['SECRET_KEY'] = b'secret'


@app.route('/login', methods=['POST'])
def login():

# Get the JSON data from the request.
formdata = request.get_json()
# Create the form using the from_json constructor
registerForm = RegisterForm.from_json(formdata=formdata)
# Return a dict, which will automatically be serialised as JSON.
if registerForm.validate_on_submit():
return {'result': 'success'}
return registerForm.errors

app.run()

显着特点:
  • 使用 wtforms_json以 wtforms 形式启用 JSON andling 的包。
  • wtforms_json.init()必须调用以将 JSON 功能添加到 Form类(class)
  • 路由处理程序在表单验证后返回 dicts; Flask 会自动将这些转换为 JSON 响应。我发现最好在呈现整个 HTML 页面的 GET 路由处理程序中呈现表单,但当仅传输 JSON 序列化数据时,使用单独的处理程序来处理来自 javascript 的请求。

  • 如果将此数据发送到应用程序,则会按预期进行错误验证:

    $ cat register.json 
    {
    "username": "Tharg",
    "email": "Banana",
    "password": "red",
    "confirm_password": "blue",
    "csrf_token": "secret"
    }
    $ curl -X POST -H "Content-Type: application/json" -d @register.json http://localhost:5000/login
    {"confirm_password":["Field must be equal to password."],"csrf_token":["The CSRF token is missing."],"email":["probably not e-mail"],"password":["the password is too simple"]}

    关于python - 使用 AJAX 时 wtforms 验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60528725/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com