首页 > 解决方案 > 如果 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")
    }

标签: javascripthtml

解决方案


使验证()返回真或假

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

推荐阅读