0

For this particular existing form there is an input to accept phone numbers. It already validates to only accept numbers and added a max character attribute for 10 characters.

However someone could add 1-9 digits. So I need to add javascript to check to make sure the character count for that field is 10. The input has an ID of phonenumber.

Can someone tell me how to modify the following code to make that work? Note: The "= 10 Characters" is just a placeholder, that part needs to be replaced with real code.

function checkEmail(theForm) { if (theForm.getElementById("phonenumber").value = 10 Characters ) { alert('Your phone number is not 10 digits.'); return false; } else { return true; } } 
1
  • 3
    Did you use a regex to prevent non-digits from being entered? Combine this to \d{10} Commented May 7, 2012 at 17:18

5 Answers 5

1

I think you want .length

if (theForm.getElementById("phonenumber").value.length == 10) { 
Sign up to request clarification or add additional context in comments.

Comments

1

You may want to be gentle with your users, and allow common conventions in phone numbers, like spaces or dash-hyphens.

Just check for 10 digits. When you use the value, remove any non digits.

function checkphone(v){ if(v.match(/\d/g).length==10) return true; throw 'Phone number must have 10 digits'; } 

checkphone('207 555-5555');

Comments

0

if (theForm.getElementById("phonenumber").value.length != 10)

...since you want something to happen if the length is not 10.

Comments

0

Verify min and max length of phone number field using Javascript Validation

function checkLimit() { var x, text; // Get the value of the input field with id="Phone" phone = document.getElementById("Phone").value; // If phone is Not a Number or less than 10 or greater than 10 if (isNaN(phone) || phone.length < 10 || phone.length > 10) { text = "Input not valid"; } else { text = "Input OK"; } document.getElementById("resp").innerHTML = text; }
 <input onkeypress="checkLimit()" id="Phone" name="Phone" type="number" class="form-control" placeholder="Phone Number" required="required"/> <p id="resp"></p>

Comments

-1

try this:

function checkEmail(theForm) { if (theForm.getElementById("phonenumber").value.length != 10 ) { alert('Your phone number is not 10 digits.'); return false; } else { return true; } 

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.