How do I validate a phone number with javascript? - javascript

Would someone a little smarter than myself be able to help me with this function? Its purpose is to validate a text input in a form, a phone number field that will only accept 0-9, dash and dot. The HTML calls the function fine.
function validateFeedback() {
var phone = document.getElementById("phone");
var validNumber = "0123456789.-";
for (i = 0; i < phone.length; i++); {
if (validNumber.indexOf(phone.charAt(i)) == -1); {
alert("You have entered an invalid phone number");
return false;
}
}
return true;
}
Thanks so much for any help.

Regular expressions should help ;)
I'm sorry I haven't tried to run this code, but it should be OK.
function validateFeedback(){
var phone = document.getElementById("phone");
var RE = /^[\d\.\-]+$/;
if(!RE.test(phone.value))
{
alert("You have entered an invalid phone number");
return false;
}
return true;
}

try like this:
function validateFeedback()
{
var phone = document.getElementById("phone");
var validNumber = "0123456789.-";
for(i = 0; i < phone.length; i++) {
if(validNumber.indexOf(phone.charAt(i)) == -1) {
alert("You have entered an invalid phone number");
return false;
}
}
return true;
}
there are ; out of place ...

I think you should use a regex to do this. Something link this:
function validateFeedback() {
var phone = document.getElementById("phone").value;
var reg = new RegExp("[0-9 .-]*");
return reg.test(phone);
}

If the text input is in a form, you can reference it more directly using the form id and the element id:
var phone = document.<formId>.phone;
What you want to test is the value of the element, so you need:
var phone = document.<formName>.phone.value;
Since the function is probably called from a submit listener on the form, you can make things more efficient using:
<form onsubmit="return validateFeedback(this);" ...>
It also seems to me that a phone number has only digits, not "-" or "." characters, so you should only test for digits 0-9.
So the function can be like:
function validateFeedback(form) {
var phoneValue = form.phone.value;
// Use a regular expression to validate the value
// is only digits
if (/\D/.test(phoneValue) {
// value contains non-digit characters
// advise user of error then
return false;
}
}
you may want to test that the length is reasonable too, but note that phone numbers in different places are different lengths, depending on the location and use of area or country codes, and whether the number is for a mobile, landline or other.

I would prefer to use regular expressions for something like this.
Please look at my modified version of your function which should work in all major browsers without any framework.
function validateFeedback() {
// Get input
var phone = document.getElementById("phone"),
// Remove whitespaces from input start and end
phone = (phone || '').replace(/^\s+|\s+$/g, ''),
// Defined valid charset as regular expression
validNumber = "/^[0123456789.-]+$/";
// Just in case the input was empty
if (phone.length == 0) {
// This depends on your application - is an empty number also correct?
// If not, just change this to "return false;"
return true;
}
// Test phone string against the regular expression
if (phone.match(validNumber)) {
return true;
}
// Some invalid symbols are used
return false;
}

Try this one
function validateFeedback(value) {
var length = value.length;
chk1="1234567890()-+ ";
for(i=0;i<length;i++) {
ch1=value.charAt(i);
rtn1=chk1.indexOf(ch1);
if(rtn1==-1)
return false;
}
return true;
}

function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}

Related

Why this regular expression return false?

i have poor eng, Sorry for that.
i'll do my best for my situation.
i've tried to make SignUpForm using regular expression
The issue is that when i handle if statement using the regular expression
result is true at first, but after that, become false. i guess
below is my code(javascript)
$(document).ready(function () {
var idCheck = /^[a-z]+[a-z0-9]{5,19}$/g; // more than 6 words
var pwCheck = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/; // more than 8 words including at least one number
var emCheck = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/; // valid email check
var signupConfirm = $('#signupConfirm'),
id = $('#id'),
pw = $('#pw'),
repw = $('#repw'),
email =$('#email');
signupConfirm.click(function () {
if(id.val() === '' || pw.val() === '' || email.val() === ''){
$('#signupForm').html('Fill the all blanks');
return false;
} else {
if (idCheck.test(id.val()) !== true) {
$('#signupForm').html('ID has to be more than 6 words');
id.focus();
return false;
} else if (pwCheck.test(pw.val()) !== true) {
$('#signupForm').html('The passwords has to be more than 8 words including at least one number');
pw.focus();
return false;
} else if (repw !== pw) {
$('#signupForm').html('The passwords are not the same.');
pw.empty();
repw.empty();
pw.focus();
return false;
}
if (emCheck.test(email.val()) !== true) {
$('#signupForm').html('Fill a valid email');
email.focus();
return false;
}
}
})
});
after id fill with 6 words in id input, focus has been moved to the password input because the condition is met.
but after i click register button again, focus move back ID input even though ID input fill with 6 words
i've already change regular expression several times. but still like this.
are there Any tips i can solve this issue?
I hope someone could help me.
Thank you. Have a great day
Do not use the global flag on your regexes. Your code should be:
var idCheck = /^[a-z]+[a-z0-9]{5,19}$/;
When you match with the /g flag, your regex will save the state between calls, hence all subsequent matches will also include the previous inputs.
use
var idCheck = /^[a-z]+[a-z0-9]{5,19}$/
removing the g flag
and modify the line
else if (repw.val() !== pw.val()) {

How to avoid to enter repeated number in input text form?

I'm trying past few days to solve input number form validation in javascript. The logic user doesn't allow to enter repeated same number like "00000000000", "11111111111". If they enter numbers on text field i have to show error message,
sample code,
var mobNumber = $('#phNo').val();
if(mobNumber.match("00000000") || mobNumber.match("1111111")) {
alert('Please enter valid phone number');
}
You could use following regex ^(\d)\1+$ :
^ asserts position at start of the string
(...) 1st capturing group
\d matches a digit (equal to [0-9])
\1 matches the same text as most recently matched by the 1st capturing group
+ Quantifier, matches between one and unlimited times, as many times as possible, giving back as needed
$ asserts position at the end of the string, or before the line terminator right at the end of the string (if any).
See following example:
function test(par){
if(par.match(/^(\d)\1+$/g)){
console.log(par + " is not valid");
}else{
console.log(par + " is valid");
}
}
test("11111111");
test("11131111");
test("111a1111");
test("010101010");
test("9999");
I hope it helps you. Bye
You can simply write code like
$(document).on('input', '#phNo', function() {
var mobNumber = $(this).val();
var res = mobNumber/(mobNumber/10);
if(res == 111111111) {
alert('Please enter valid phone number');
}
});
this is applicable for all numbers and you have to check the max and min length of the input ..
You can try like this,
var phone = "11111111";
var phonecount = phone.length;
var countLength = 0;
for (var i in phone)
{
if(phone.substring(0,1)==phone[i])
{
countLength = countLength + 1;
}
}
if (countLength == phonecount)
alert("Please enter valid phone number");
try this :
var checkPhone = function() {
phone_number = $('#phone').val();
res = (/^(.)\1+$/.test(phone_number) ? '1' : '0');
if(res == '1'){
return 'bad phone number';
} else {
return 'good phone number';
}
}
Test it here : JSFIDDLE

JavaScript phone number validation using charCodeAt

I'd like to validate a phone number input using JavaScript to allow only number input. I prefer not to use regex, so I wrote a function like this:
function numberTest(){
for(var i=0;i<phone_number.length;i++){
if(phone_number.charCodeAt(i) >= 48 && phone_number.charCodeAt(i) <=57){
return true;
}else{
return false;
}
}
}
However it does not work. Any ideas why?
This doesn't work because it returns true after the first valid character. Neither branch will get past the first character, so you need to only return if you find an invalid character. Otherwise, if you reach the end without finding an invalid characters, you can finally return true.
Something like:
function numberTest(phone_number) {
for (var i = 0; i < phone_number.length; i++) {
if (phone_number.charCodeAt(i) < 48 && phone_number.charCodeAt(i) > 57) {
return false;
}
}
return true;
}
// Test various values
var testData = ["1234", "12ab", "123451234512345", "a1234123", "123123123a"];
var output = document.getElementById("results");
testData.forEach(function(test) {
var next = document.createElement("li");
next.textContent = numberTest(test);
});
<ul id="results"></ul>
The isNaN() (means is not a number) method will give you the reverted result in a simpler way...
var phone_number = "5511112223";
alert(isNaN(phone_number)); //returns false meaning it is a valid number
phone_number = "55aa1g11d12223";
alert(isNaN(phone_number)); //returns true meaning it is not a number

how validate an email that allows specific number of dots before and after # symbol

var val_em=document.add_indus_detail_form.txt_email.value;
var atpos=val_em.indexOf("#");
var dotpos=val_em.lastIndexOf(".");
if(val_em!='')
{
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=val_em.length)
{
alert("Not a valid e-mail address");
return false;
}
}
i use this condition to check the email validation that user enters in the textbox how i can validate it like it allows 3 or 4 or any specific numbers of dot allow (ex abc.abc.abc.abc#abc.abc.com) before and after the # but do not allow that dots together (ex: abc#abc...com). also do not allow the spaces in email how it will be have you any idea for this type of validation..
I would suggest a regex for this
function validateEmail(email){
var emailReg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
var valid = emailReg.test(email);
if(!valid) {
return false;
} else {
return true;
}
}
call the function validateEmail whenever you need....
Validations in JavaScript are useless. The user can turn off JS or maybe you encounter a browser who cant even understand JS. This makes your page vulnerable to attacks. So NEVER use JS for validating user inputs.
What you want is RegEx or many if-conditions together with string-functions. My approach: Use a For-Loop, go through the string one by one, check the current character and the one after it. Like this:
for($i = 0; $i < strlen($string); $i++) {
if(substr($string, 0, 1) == '.' {
//do something
}
}

jQuery Tools Validator - regex test - exclude just letters

i'm trying to validate a field to include everything except letters but the following only works on the first character i enter. So if i enter '123a' the test method returns true.
$.tools.validator.fn("input#Phone", "Please enter a valid phone number.", function(input, value) {
var pass;
var rgx = /[^a-z]/gi;
if ( rgx.test(value)
|| (value == "")
|| (value == $(input).attr("placeholder"))) {
$(input).removeClass("invalid");
pass = true;
} else {
$(input).addClass("invalid");
pass = false;
}
return pass;
}
You're only matching against a single character.
/^[^a-z]$/i
This ensures that the entire string is non-letters.
for only numeric:
RegExp(/^[^a-zA-Z]$/i)
for phone number you can use
RegExp(/^[0-9 -()+]{6,20}$/i)

Categories

Resources