简体   繁体   English

使用getElementById在javascript中使用正则表达式进行HTML表单验证?

[英]Html form validation with regex in javascript using getElementById?

I want to validate an html form using regex for this example pattern: AAA.111#2222_aa-1234 我想针对此示例模式使用正则表达式验证html表单: AAA.111#2222_aa-1234

Currently my code is either returning "correct" for all input or "incorrect" for all input, and I cannot figure out where my issue is. 当前,我的代码要么对所有输入都返回“正确”,要么对所有输入都返回“不正确”,但我无法弄清楚问题出在哪里。

  var x = document.getElementById("myForm"); function regExp(courseNum) { var vCourse = /([AZ]{3})\\.(\\d{3})#(\\d{4})_([az]{2})-(\\d{4})/; return (vCourse.test(courseNum)); } function isValid() { if (regExp(x)) { document.getElementById("demo").innerHTML = "Correct Format"; } else { document.getElementById("demo").innerHTML = "Incorrect Format"; } } 
 <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <h3>Please enter your course number below</h3> <form id="myForm"> Course: <input type="text" name="course" id="course"><br> </form> </br> <button onclick="isValid()">Validate</button> <p id="demo"></p> <script src="course.js"></script> </body> </html> 

I'm in the middle of a javascript course and haven't covered many javascript concepts yet, so I'd like to use the knowledge we have covered up to this point. 我正在上一门javascript课程,还没有涉及很多javascript概念,所以我想利用到目前为止所学的知识。

Any help with this is greatly appreciated! 任何帮助,我们将不胜感激!

You are very close! 你很亲密! Just two changes to get things working. 只需进行两项更改即可使工作正常进行。 First you are selecting your form to get the value of. 首先,您要选择表格以获取其价值。 You want to select the input instead so change "myForm" to "course" . 您想选择输入,因此将"myForm"更改为"course" The second thing is that you need to get the value of the input. 第二件事是您需要获取输入的值。 Right now you are trying to validate the DOM element itself, but you should be validating the value property of the input element. 现在,您正在尝试验证DOM元素本身,但是您应该在验证输入元素的value属性。 So change regExp(x) to regExp(x.value) . 因此将regExp(x)更改为regExp(x.value)

 var x = document.getElementById("course"); // First Change function regExp(courseNum) { var vCourse = /([AZ]{3})\\.(\\d{3})#(\\d{4})_([az]{2})-(\\d{4})/; return (vCourse.test(courseNum)); } function isValid() { if (regExp(x.value)) { // Second Change document.getElementById("demo").innerHTML = "Correct Format"; } else { document.getElementById("demo").innerHTML = "Incorrect Format"; } } 
 <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <h3>Please enter your course number below</h3> <form id="myForm"> Course: <input type="text" name="course" id="course"><br> </form> </br> <button onclick="isValid()">Validate</button> <p id="demo"></p> <script src="course.js"></script> </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM