javascript - 使用 If Else 语句和 document.getElementByID 进行表单验证

标签 javascript html css forms validation

我是这个网站的新手,但上周我一直在网上搜索这个问题的答案,但我似乎找不到答案。

我想要的是表单中 3 个字段中的 2 个在单击提交按钮时进行验证,而不是转到下一页,它需要在允许之前进行验证。

这是我的,

HTML:

function validateForm(input) {
  var isValid = true;
  if (!document.getElementById("Name").value.trim().length) {
    isValid = false;
    alert("Please enter your First Name");
  } else if (!document.getElementById("Comment1").value.trim().length) {
    isvalid = false;
    alert("Please enter your phone number");
  } else {
    return false;
  }
  if (isValid) {
    document.getElementById('ICContainer').style.display;
    loadInstantChat();
  }
}
input[type=submit] {
  position: relative;
  top: 20px;
  width: 322px;
  background-color: #EF423E;
  border-radius: 5px;
  border: none;
  color: white;
  padding: 4px;
  font-family: 'arial';
  font-size: 11pt;
  text-decoration: double;
  margin: 4px 2px;
  cursor: pointer;
}

input[type=text],
[type=number],
[type=email] {
  width: 323px;
  padding: 4px 4px;
  margin: 8px 0;
  box-sizing: border-box;
  border: solid #EF423E 2px;
  border-radius: 5px;
  color: #4E4E56;
  background-color: #f9f9f9;
  font-family: 'arial';
  font-size: 11pt;
}
<body onload="handleRebootOrRefresh();">
  <form name="input" action="#" onsubmit="return validateForm(input)" method="post">
    Your first name:* <input id="Name" type="text" name="inputName"> Your phone number:* <input id="Comment1" type="text" name="inputNumber"> Claim Reference: <input id="Comment2" type="text" name="inputClaim">
    <input type="submit" value="Chat Now" onclick="validateForm(input)">
  </form>

  <div id="ICContainer" style="position: absolute; left: 0px; top: 0px; width: 350px; height: 550px; display: none"></div>
</body>

这段代码中运行了很多我不想触及的其他 JavaScript,但我确实需要知道如何让前 2 个字段进行验证,如果验证成功,它会处理到下一页(即 document.getElementByID('ICContainer').style.display; loadInstantChat();

明确地说,这是一个 LogMeIn Rescue 即时聊天实例,他们的支持热线是“不要触摸任何东西,即使我们确实为您提供了分步指南”。

最佳答案

可以使用函数的返回值来阻止表单提交

<form name="myForm" onsubmit="return validateMyForm();"> 

功能类似

<script type="text/javascript">
function validateMyForm()
{
  if(check if your conditions are not satisfying)
  { 
    alert("validation failed false");
    returnToPreviousPage();
    return false;
  }

  alert("validations passed");
  return true;
}
</script>

关于javascript - 使用 If Else 语句和 document.getElementByID 进行表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42348747/

相关文章:

html - youtube 弹出窗口的自定义关闭按钮

javascript - 如何使用 jquery get select 元素具有 MULTIPLE 模式和反向

javascript - 如何访问并重新加载此 iframe?

javascript - 悬停效果和IE bug

javascript - WebDriver.io 没有控制台输出

javascript - Azure 聊天机器人 token 服务器

javascript - js中的Url.RouteUrl

javascript - 如何将类应用(和更改)到已存在的 SVG 元素

css - 如何将 SASS 转换为 CSS?

html - 仅使用 HTML 和 CSS 将文本元素替换为淡入淡出动画