javascript - 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>
当我单击提交按钮时,它正在检查并显示模式匹配结果,但数据在有效和无效情况下都在传递。
谁能帮我解决这个问题。
解决方案
不要调用myFunction()
提交按钮的onclick
属性。表单验证发生在提交表单时,也就是onclick
函数返回之后。在表单的onsubmit
属性中执行此操作。
<form method="POST" onsubmit="myFunction(); return false;">
您也应该使用return false;
,否则表单将正常提交,即使您已经使用 AJAX 发送了数据。
推荐阅读
- vue.js - Vuejs 检查方法中的空值或未定义值
- python - 熊猫匹配算法
- java - 无法使用json值包含\\的jackson的objectMapper解析json
- python - 得到“SyntaxError: Invalid Syntax”,但不知道为什么
- spring-boot - SpringBoot 2.1.3 首次认证的安全多重可用登录页面
- javascript - 为什么括号用于在元素的 onClick 标记内调用函数,而不是在元素的 onclick 属性中?
- java - JACOB - 对 COM 接口的远程调度调用
- android - 发送到本地 IP 地址时出现明文错误——Android 9
- c# - 使用 xsd.exe 从架构生成的类不包含枚举值
- c - 使用 C 中字符数组中的字符进行多线程读取/处理