使用setCustomValidity提示表单不能为空的问题

kinged87 kinged87 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
最近开始学习HTML,学到setCustomValidity,根据书上的,写了一个例子,代码如下:
<!DOCTYPE html>
<html>
<head>
<title>欢迎来到我的空间</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<form action="http://www.baidu.com" method="get">
<label for="userId">用户名:</label><input id="userId" type="email" name="userId" placeholder="邮箱/用户名" autocomplete="off" /></br></br>
<label>密  码:<input id="passwd" name="passwd" type="password" autofocus placeholder="密码"/></label><br/><br/>
<input id="ok" name="ok" type="submit" value="提交" onclick="return check();"/>
</form>
<script type="text/javascript">
var check = function()
{
return commonCheck("userId" , "邮件地址" , "字段必须符合电子邮件的格式!");
}
var commonCheck = function(field , fieldName , tip)
{
var targetEle = document.getElementById(field);
// 如果该字段的值为空
if (targetEle.value == "")
{
//alert(fieldName + "字段必须填写!");
targetEle.setCustomValidity(fileName+tip);
return false;
}
// 调用checkValidity()方法执行输入校验
else if(!targetEle.checkValidity())
{
targetEle.setCustomValidity(fileName+tip);
//alert(fieldName + tip);
return false;
}
return true;
}
</script>

</body>
</html>
我标成红色那一行不执行,如果为空,点击提交,直接就跳转了,但是如果输入不为空,可以判断。而且,为空的换成alert判断,也可以,这是怎么回事,应该怎么改。
...全文
评论 1
收藏 已收藏
分享
返回顶部
kinged87
CSS 61,117 成员 60,701 内容