-1

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

  • You can use the following link:- https://stackoverflow.com/questions/18375929/validate-phone-number-using-javascript – maverick May 16 '20 at 18:22
  • @universedecoder Thank you, and i have already seen that...but i want to know how to implement that in my form so that it doesn't submit. Where do i add my function call ...please be more specific – Vishruth Subramanian May 16 '20 at 18:29
  • Normally one specifies `enctype="multipart/form-data"` when one is submitting a form that includes a file upload. That does not seem to be the case here. – Booboo May 16 '20 at 21:01

2 Answers2

1

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

Khader Handal
  • 78
  • 1
  • 10
1

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>
Booboo
  • 38,656
  • 3
  • 37
  • 60