如果未通过客户端验证,则阻止HTML表单发布

时间:2019-10-15 21:41:13

标签: javascript html

基本上,我有一个非常简单的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")
    }

2 个答案:

答案 0 :(得分:1)

使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;
}

答案 1 :(得分:0)

<!DOCTYPE html>
 <html>
 <body>
 <form name="registro" action="/productos" method="post">
 <div>titulo</div>
 <input type="text", name="titulo" required="required" />
 <input type="submit">
 </form> 
 </body>
 </html>

不需要javascript来运行。

使用具有xhtml兼容性方法的标准html5这样的表单验证更为容易:

 <!DOCTYPE html>
 <html>
 <body>
 <form name="registro" action="/productos" method="post">
 <div>titulo</div>
 <input type="text", name="titulo" required="required" />
 <input type="submit">
 </form> 
 </body>
 </html>