1

Hi I am new to HTML and JavaScript. I want to check the users phone number input for any letters, and print out those letters within the error message.

I'm a bit lost at the moment, can I save input as a string (as shown by the pseudo code saving input as InsertLetter). As well as put any string characters that are letters into an error message?

<form onsubmit="return isnumb()">
<label for="ph"> Enter Phone: </label>
            <input type="text" id="phnumb"> <span 
            id="message"></span>
     //InsertLetter = phnumb output
</form>
<script>
 function isnumb() {
if (document.getElementById("phnumb").match =([a-z]))
   {document.getElementById("message").innerHTML = 
   "<em> Number includes letter" + InsertLetter + "</em>";
         return false;}
else return true;
Crocs123
  • 105
  • 7
  • 1
    You are looking for regex. To match any letter: `/[a-zA-Z]/` – Justinas Sep 17 '20 at 06:04
  • Does that code work? "phnumb").match =([a-z]) is calling match on a DOMelement which doesn't exist as far as I know. "0123".match called on a string does so it would look like ...byId('phone').value.match(/regex/) returns true or false in your if clause. – progonkpa Sep 17 '20 at 07:34
  • See here: https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation – AbsoluteBeginner Sep 17 '20 at 07:38

3 Answers3

2

It is far better to use <input type="tel"> in this situation. On that occasion user input should follow the given pattern which you can check with. Use Form Validation for the rest of the work, for example:

const phone = document.getElementById("phone");
const button = document.getElementsByTagName('button')[0];
const errorMessage = document.querySelector('p.error');

button.addEventListener('click', (e) => {
  if (!phone.validity.valid) {
    showError();
    e.preventDefault();
  }
});
phone.addEventListener('keyup', (e) => {
  if (phone.validity.valid) {
    errorMessage.innerHTML = '';
  } else {
    showError();
  }
});

function showError() {
  if (phone.validity.valueMissing) {
    errorMessage.textContent = "Phone is required";
  }
  if (phone.validity.patternMismatch) {
    errorMessage.textContent = "You are not supposed to use characters like this one: " + phone.value;
  }
  if (phone.validity.valid) {
    phone.setCustomValidity("");
  }
}
.error {
  color: red;
}
<form>
  <label for="phone">Phone Number (Format: +99 999 999 9999)</label>
  <input type="tel" id="phone" name="phone" pattern="[\+]\d{2}[\s]\d{3}[\s]\d{3}[\s]\d{4}" required>
  <p class="error"></p>
  <button>Submit</button>
</form>
  • 1
    I didn't know about phone API. It looks really good. The pattern is a regular expression which is definitely the way to go. I always use this webtool to find out the right regex regexr.com – progonkpa Sep 17 '20 at 07:22
  • 1
    @progonkpa check the documentation links given in the answer, from the provided examples there you will get even more ideas on how to validate all your form items and create some nice visual effect to display the message upon error or success (if you want). –  Sep 17 '20 at 07:30
0

First of all i want to give u an answer of user should insert only number :`

 <!DOCTYPE html>
<html lang="en">
  <head>
    <script>
      function submitForm() {
        var phonenumber = document.forms["myForm"]["notanumber"].value;
        if (isNaN(phonenumber)) {
          alert("only number required");
        } else {
          alert("submit");
        }
      }
    </script>
  </head>
  <body>
    <form id="myForm">
      <input type="text" id="notanumber" />
      <input type="submit" onclick="submitForm()" />
    </form>
  </body>
</html>

-> isNaN() is an inbuilt function in js, if variable is not a number, it return true, else return false.

Tanmay Brv
  • 89
  • 4
  • I wouldn't recommend using `isNaN` because it has some weird quirks ([example](https://stackoverflow.com/q/825402/2093695)). Especially since not all phone numbers are numbers (e.g. `isNaN("(541) 754-3010")` returns true`). – Brian McCutchon Sep 17 '20 at 06:43
0

the simple code : restric the user from clicking any key, Only numbers allowed.

<!DOCTYPE html>
<html lang="en">
  <head>
    <script>
      function submit() {
        alert("submited");
      }
      function noAlphabets(e) {
        var phonenumber = document.forms["myForm"]["notanumber"].value;
        var x = e.which || e.keycode;
        if (x >= 48 && x <= 57) {
          return submit();
        } else {
          alert("insert only numbers");
          return false;
        }
      }
    </script>
  </head>
  <body>
    <form id="myForm">
      <input
        type="text"
        id="notanumber"
        onkeypress="return noAlphabets(event)"
      />
      <button type="button" onclick="submit()">Submit</button>
    </form>
  </body>
</html>
Tanmay Brv
  • 89
  • 4