JavaScript
Article
By Sam Deering

A jQuery Script to Check if a String is a Phone Number or Email Address

By Sam Deering
Last chance to win! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

Here’s a simple jQuery code snippet to check if a string is either a phone number or email address. It could be very useful for checking form validation. You can then have a input called “Email or Phone” then on submit check the value and if its a phone number then set value to the phone input and clear email input before form submit.

--ADVERTISEMENT--

jQuery Code

//validate name
var name = $('input[name="name"]').val();
if (name.length Phone or email
[js]
//check if they entered a phone number OR email address
var ep_emailval = $('#email').val();
var intRegex = /[0-9 -()+]+$/;
if(intRegex.test(ep_emailval)) {
   console.log("is phone");
   //copy value to phone field
   $('#phone').attr('value',ep_emailval);
   //clear email field
   $('#email').attr('value','');
}

HTML Code

//check if they entered a phone number OR email address
Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?