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")
}
解决方案
使验证()返回真或假
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;
}
推荐阅读
- .net - 有没有办法获取当前 raygun 中的所有错误?
- python - 在关于 argparse.ArgumentParser() 的 google colab 错误上执行代码时
- html - 真实的例子
- java - 我的映射器接口中是否可以有多个方法,几乎相同但返回对象不同?
- arrays - Shopify JSON 类型元字段循环不起作用
- sql - 如何对依赖于内连接表信息的表应用安全策略?
- environment-variables - 赛普拉斯,不同的 baseURL 和用户名
- android - 无法在使用 CI/CD 工具获取的真实设备中启动 apk。(无法实例化应用程序)
- android-studio - 代码片段漂浮在半空中作为工具提示,无法隐藏,提取方法后 [IntelliJ Idea / Android Studio]
- reactjs - React js悬停元素并在离开元素时禁用悬停