[英]How to validate phone number in a form: JavaScript
I am building a web application with NodeJS and express.我正在使用 NodeJS 和 express 构建一个 web 应用程序。 I am having a form that submits a POST request on submission.
我有一个在提交时提交 POST 请求的表单。 How do i validate the "phone" input so that phone number is 10 digits.
我如何验证“电话”输入,以便电话号码为 10 位数字。
<form action="/books" method="POST" enctype="multipart/form-data">
<input class="form-control" type="text" name="user[name]" placeholder="name" required>
<input class="form-control" type="number" name="user[phone]" placeholder="phone" required>
<button>Submit</button>
</form>
The user must not be able to submit if the phone number is invalid.如果电话号码无效,则用户不得提交。
Any help is very much appreciated很感谢任何形式的帮助
Did you try this code:你试过这段代码吗:
function phonenumber(inputtxt) {
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno)) {
return true;
} else {
alert("message");
return false;
}
}
Full details of the above code was taken from W3Resource上述代码的全部细节取自W3Resource
Here is a JSfiddle page for a sample how it should look like: https://jsfiddle.net/khaderhan/5phbg26n/15这是一个 JSfiddle 页面,用于示例它应该是什么样子: https://jsfiddle.net/khaderhan/5phbg26n/15
The following is a code snippet to demonstrate how to validate the form using an onsubmit
handler.以下是演示如何使用
onsubmit
处理程序验证表单的代码片段。 Normally you would output a message to the user with a call to alert
.通常,您会 output 向用户发送消息并调用
alert
。 But since that is not supported in these code snippets, I have used calls to console.log
instead.但由于这些代码片段不支持这一点,因此我改用对
console.log
的调用。
I've also used a validation technique that allows you to used a regular input field that would allow the user to enter non-digit characters and verifies that the number of digits is 10 so that the user could enter for example: (555)555-5555.我还使用了一种验证技术,允许您使用常规输入字段,允许用户输入非数字字符并验证数字位数是否为 10,以便用户可以输入例如:(555)555 -5555。 Of course, it still works with a field that only permits digits.
当然,它仍然适用于只允许数字的字段。
function validateForm() { let phone = document.f['user[phone]'].value; phone = phone.replace(/\D/g, ''); // get rid of all non-digits if (phone.length == 10) { return true; } //alert('Invalid phone number'); console.log("Invalid phone number."); // alert not supported in code snippet return false; }
<form name="f" action="/books" method="POST" enctype="multipart/form-data" onsubmit="return validateForm();"> <input class="form-control" type="text" name="user[name]" placeholder="name" required> <input class="form-control" type="number" name="user[phone]" placeholder="phone" required> <button type="submit">Submit</button> </form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.