首页 > 解决方案 > html中的字符串模式验证

问题描述

我曾经编写过将字符串传递给 api 的代码。这个stings必须满足一些模式,然后如果它满足模式,它必须通过单击一个按钮来调用一个api来存储这个字符串。

将字符串传递给数据库

<link rel="stylesheet" type="text/css" href="css/style.css"> 
<style> 
body{
  background: url("images/background.jpg");
  background-size: cover;
 }

<div class="data" >
   <h1>SignUp Here</h1>

        <form   method = "POST" >

        <p>Username</p>
        <input type="text" name="citycode" placeholder="Enter citycode"   id="citycode"  pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 6 or more characters">
        <p>Password</p>
         <input type="code2" name="countrycode" placeholder="Enter countrycode" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 6 or more characters" id="countrycode">
        <button type="submit" name="submit" onclick="myFunction()">Submit</button> </br> </br> </br>
        </form>
    </div>

</body>
<script type="text/javascript">

function myFunction() {
  var citycode, countrycode;
  city = document.getElementById('citycode').value;
  country = document.getElementById('countrycode').value;
  var xhttp = new XMLHttpRequest();
  var url = "https://my api url";
  var sending = JSON.stringify({
    "citycode": city,
    "countrycode": country
  });
  xhttp.open("POST", url, true);
  xhttp.send(sending);
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      console.log("status success");
      alert(xhttp.responseText);
    }
  };
  //}
}

</script>


</html>

当我单击提交按钮时,它正在检查并显示模式匹配结果,但数据在有效和无效情况下都在传递。

谁能帮我解决这个问题。

标签: javascripthtml

解决方案


不要调用myFunction()提交按钮的onclick属性。表单验证发生在提交表单时,也就是onclick函数返回之后。在表单的onsubmit属性中执行此操作。

<form method="POST" onsubmit="myFunction(); return false;">

您也应该使用return false;,否则表单将正常提交,即使您已经使用 AJAX 发送了数据。


推荐阅读