Shasha
Shasha

Reputation: 433

Detect if user is typing an email or number with javascript or jquery

How do I detect if a user is typing a phone number or email address as the user typing from the first three inputs.

I am creating a login in system for my company

I need this to format the users phone number when is user is typing automatically.

PS:I already know how to do the formatting in the form I want

WORTHY NOTE: emails could also come in [email protected] or [email protected] how can I detect.

Is it possible

Lets say I have

<input type="text" placeholder="Phone number or Email" id="number_or_email" onkeyup="fire_after_first_three()">

function fire_after_first_three(){
//do number formatting on the go or ignore user input if email
}

Where the USER can either use Phone Number or Email address to login.

The expected input from the user is: for phone number XXXXXXXXXXX which I do format to XXX-XXXX-XXXX or email [email protected] which is checked at the backend.

I need to know user input, so that I can format the phone number on fly if the user decides to use phone number to log in.

Upvotes: 0

Views: 1671

Answers (1)

DecPK
DecPK

Reputation: 25408

I've taken the length of the phone no as 11. You can validate the after 3 input as I've started as soon as user start inserting input.

function validateEmail(email) {
  const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(String(email).toLowerCase());
}

function validateOnlyNumbers(phone) {
  return phone.match(/^\d+$/);
}

const input = document.querySelector("input");
const h1 = document.querySelector("h1");

input.addEventListener("keyup", e => {
  const value = e.target.value;

  if (validateOnlyNumbers(value)) {
    if (value.length === 11) {
      h1.textContent = "Phone Number"
      // Format input acc to phone no
    } else {
      h1.textContent = "could be Phone Number"
    }
  } else {
    if (validateEmail(value)) {
      h1.textContent = "Email"
      // Format input acc to Email
    } else {
      h1.textContent = "could be Email"
    }
  }
})
<input type="text" />
<h1></h1>

Upvotes: 3

Related Questions