[英]Javascript Validation not Working with Regular expression
我的javascript验证器不起作用。 当我什么也没输入时,不显示警报。 另外,你们可以向我解释一下表格的动作方法是什么以及我应该如何使用它?
<form method = "post" id = "my_form">
<h1> Thank you for visiting our website! Please take some time to fill out our service questions! </h1>
<h2> The ratings given are F, D, C, B and A. </h3>
<h3> How would you rate the service that this webpage provides?? </h3>
<input type = "text" font-size = "15px" id = "name">
<h3> How would you rate the organization and usability of this webpage?? </h3>
<input type = "text" font-size = "15px" id = "name">
<h3> How would you rate the professionalism of this webpage?? </h3>
<input type = "text" font-size = "15px" id = "name">
<h3> How would you rate the overall look of this webpage??</h3>
<input type = "text" font-size = "15px" id = "name">
<br /><br />
<input type = "submit" id = "submit" value = "submit" name = "submit">
</form>
<script type = "text/javascript">
var my_form = document.getElementById("my_form");
my_form.addEventListener("submit", function(event) {
var name = document.getElementById("name").value;
var tomatch = /[a-f]/i;
if (!tomatch.test(name)) {
event.preventDefault();
window.alert("The name can only contain letters from a-f");
}
}. false);
</script>
您有几个具有相同ID的输入,并且此处的语法错误不正确
my_form.addEventListener("submit", function(event) {
// bunch of code...
}. false); // <-- not dot, but comma
检查下面的解决方案
document.getElementById("my_form").onsubmit = function(event) { var tomatch = /[af]/i; //var name = document.getElementById("name").value; // you can also get value like this var name = document.forms.my_form.name.value if (!tomatch.test(name)) { event.preventDefault(); window.alert("The name can only contain letters from af"); } }
<form method="post" id="my_form" method="post" action"/my-url"> <input type="text" font-size="15px" id="name"> <input type="submit" id="submit" value="submit" name="submit"> </form>
用于正则表达式使用
var tomatch = new RegExp("/[a-f]/i");
问候。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.