gpt4 book ai didi

javascript - 如果未通过客户端验证,则阻止 HTML 表单进行 POSTing

转载 作者:行者123 更新时间:2023-12-02 22:45:54 25 4
gpt4 key购买 nike

基本上,我有一个非常简单的 HTML 表单,当我提交时,它会 POST 到/productos 并运行一个 JS 脚本来验证表单,如果它不正确,它会显示一个错误,一切都很好。

但是我想做的一件事是,如果表单未通过验证,则“取消”POST,有什么办法可以做到吗?

我曾考虑过从 javascript 函数而不是从表单本身进行 POST,但我不知道该怎么做

html:

<form name="registro" action="/productos" method='post' onsubmit="return validacion()">
<div>titulo</div>
<input type="text", name="titulo"/>
<input type="submit">
</form>

js验证:

function validacion(){
var titulo=document.registro.titulo.value;
if (titulo == ""){
alert("error, titulo cant be empty")

} else if (titulo.length > 100){
alert("error, titulo cant be more than 100 characters long")
}

最佳答案

使 validacion() 返回 true 或 false

function validacion(){
var titulo=document.registro.titulo.value;
if (titulo == ""){
alert("error, titulo cant be empty")
return false;

} else if (titulo.length > 100){
alert("error, titulo cant be more than 100 characters long")
return false;
}

return true;
}

关于javascript - 如果未通过客户端验证,则阻止 HTML 表单进行 POSTing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58403008/

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