简体   繁体   中英

How to validate phone number in a form: JavaScript

I am building a web application with NodeJS and express. I am having a form that submits a POST request on submission. How do i validate the "phone" input so that phone number is 10 digits.

<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

Here is a JSfiddle page for a sample how it should look like: https://jsfiddle.net/khaderhan/5phbg26n/15

The following is a code snippet to demonstrate how to validate the form using an onsubmit handler. Normally you would output a message to the user with a call to alert . But since that is not supported in these code snippets, I have used calls to console.log instead.

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. 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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