I have been attempting to validate an australian phone number using javascript however it has been accepting everything. It needs to be 10 numbers long beginning with 0 accepting spaces:
02 4345 2334
and together
0243452334.
I think the regex might be wrong or the code itself
function PhoneNumberVal(form){
var phoneFormat= /^0[0-8]{2})\)?[ ]?([0-9]{4})[ ]?([0-9]{4})$/;
var phoneLength = document.getElementById('phone').value.length;
if(phoneFormat.test(phoneLength)) {
return true;
} else {
alert("Not a valid phone number");
return false;
}
}
Your regex is wrong. ^0[0-8]{2})\)?[ ]?([0-9]{4})[ ]?([0-9]{4})$ you failed to put the opening parenthesis and you need to change [0-8]{2} to [0-8], since your input contains exactly 10 digits.
^(?:\(0[0-8]\)|0[0-8])[ ]?[0-9]{4}[ ]?[0-9]{4}$
DEMO
Use this Regex,
/^\D*0(\D*\d){9}\D*$/
Demo
Regex? Ha! Now you have two problems.
UPDATE: This version should be final.
Just do this:
function IsAustralianTelephoneNumberValid(a_telephone)
{
a_telephone = a_telephone.replace(/\s/g, ''); // remove all spaces
// if is empty OR first char is NOT 0
if((a_telephone=='')||(a_telephone.charAt(0)!='0'))
{
alert("Not a valid phone number");
return false;
}
// lets save the length of that string before we remove digits
length_with_digits = a_telephone.length;
// now string has its digits removed
a_telephone = a_telephone.replace(/0|1|2|3|4|5|6|7|8|9/g,'');
// if is nothing, then there was no other characters in string
// except digits and spaces AND ALSO if the difference of length before the digits
// removal and now is 10 then we can be sure we had 10 digits and nothing else,
// so its valid. Any other case is not valid.
if((a_telephone=='')&&(length_with_digits-a_telephone.length==10))
{
alert('ok');
return true;
}
else
{
alert("Not a valid phone number");
return false;
}
}
http://jsfiddle.net/L7vzL4jm/10/
Related
I wrote a simple code in javascript that was supposed to validate the length of a phone number inputed in an html form (check if it consists of 10 digits- as it is in my country).
So here's the function:
function check_tel(){
var tel=document.LpData.phone.value;
var i=0;
for(;i<10;i++){
tel/=10;
if(tel==0){
alert("unvaild phone number- too short");
return false;
}
}
if(tel>0){
alert("unvaild phone number- too long");
return false;
}
return true;
}
But it always outputs that the number is too long (i>10).
I already checked the value of "tel" variable before it enters the loop and everything is right.
I also tried it with a "while" instead of "for" loop.
So I concluded it's because of the "/" operator which doesn't work (although I still don't understand how it's possible) or it has something to do with the type of tel...
So what is the problem and how to fix it?
Thanks in advance!
Every input value is always a string. Using the divide operator on a string is not what you wanted. So you may convert the phonenumber to an int:
function check_tel(){
var tel=parseInt(document.LpData.phone.value,10)||0;
for(var i=0;i<10;i++){
tel/=10;
if(tel<1){
alert("unvaild phone number- too short");
return false;
}
}
tel/=10;
if(tel>1){
alert("unvaild phone number- too long");
return false;
}
return true;
}
also note that 123456789/10000000 is not 0...
and by the way, it is much easier to simply check for tel.length...
The best practice to do these things is to use a Regular Expression(Regex).
/^\d{10}$/ is a JS regex to check if the number is a 10 digit number.
function check_tel()
{
var tel = document.LpData.phone.value;
var teleRegex =/^\d{10}$/;
if(!teleRegex.test(tel)){
alert("invalid phone number")
}
else{
//do your thing
}
}
Possible work-around is
function check_tel()
{
var tel=document.LpData.phone.value;
if(tell.length == 0 || tell.length > 10){
alert("invalid phone number");
return false;
}
return true;
}
Try var tel = parseInt(document.LpData.phone.value); instead of var tel = document.LpData.phone.value;
Here is a validation code that I use to validate mobile number. If I enter a mobile number with alphabets or any invalid number, it accepts that too. Can someone suggest what is wrong in this?
Thanks
var g=document.getElementById('mobile').value;
if (g.length == 0 )
{
alert( "Please Enter Mobile Number." );
formn.mobile.focus();
return false;
}
if(g.length>0)
{
if((g.length<10)||(g.length>10))
{
alert( "Mobile number should be 10 digits");
document.getElementById('mobile').focus();
return false;
}
else
{
var h3=/^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$/;
if(g.match(h3)!=null)
{
alert( "Please Enter Valid Mobile Number");
document.getElementById('mobile').focus();
return false;
}
}
}
EDIT : I was thinking of removing the condition of 10 digits and allow user to input the mobile numbers as per their choice and their own way and then replace/reformat using a regex so that only 10 digits mobile number goes into the database. During google search I found somewhere on stackoverflow that ^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$ works well for reformating in following scenarios. Appreciate if someone can help me reformat it and show the reformatted digits when the user goes into the next textbox (losing focus)
9883443344
09883443344
919883443344
0919883443344
+919883443344
+91-9883443344
0091-9883443344
+91 -9883443344
+91- 9883443344
+91 - 9883443344
0091 - 9883443344
Use Below code :-
var g=document.getElementById('mobile').value;
if (g.length == 0 )
{
alert( "Please Enter Mobile Number." );
formn.mobile.focus();
return false;
}
if(g.length>0)
{
if((g.length<10)||(g.length>10))
{
alert( "Mobile number should be 10 digits");
document.getElementById('mobile').focus();
return false;
}
else
{
var h3=/^[1-9]{1}[0-9]{9}$/;
if(h3.test(document.getElementById('mobile').value) == false)
{
alert( "Please Enter Valid Mobile Number");
document.getElementById('mobile').focus();
return false;
}
}
}
Updated your regex code.
why not just use [0-9] as a regex, basicly if it is not in 0-9 it is invalid, maybe you want + for international calls that is 00 infront of phone number..
Please check out these testers also if you have not already:
http://www.regexpal.com/
https://regex101.com/
http://www.regexr.com/
var re = /[0-9+]/g;
var str = '0700';
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
If it is not in found with /[0-9+]/g it is not legal
This regular expression fits for all use-cases you mentioned and strictly rejects other patterns.
((00)|\+|0)?((91)|0)?\s{0,2}-?\s{0,2}(\d{10})
I am trying to figure out if a user has entered an email id or a phone number. Therefore i would like to check if the string starts with +1 or a number to determine if it is a phone number . If it is not either i come to the conclusion it is an email or i could check if it starts with a alphabet to be sure. How do i check this . I am horrible with regex if that is the soln .
You can do this with RegEx, but a simple if statement will work as well, and will likely be more readable. If an # character is not present in the string and the first character is a number, it is reasonable to assume it's a phone number. Otherwise, it's likely an email address, assuming an # is present. Otherwise, it's likely invalid input. The if statement would look like this:
if(yourString.indexOf("#") < 0 && !isNaN(+yourString.charAt(0) || yourString.charAt(0) === "+")) {
// phone number
} else if(yourString.indexOf("#") > 0) {
// email address
} else {
// invalid input
}
if (!isNaN(parseInt(yourstrung[0], 10))) {
// Is a number
}
Just do the following:
if ( !isNaN(parseInt(inputString)) ) {
//this starts with either a number, or "+1"
}
Might I suggest a slightly different approach using the regex email validation found here?
if(validateEmail(input_str)) {
// is an email
} else if(!isNaN(parseInt(input_str))) {
// not an email and contains a number
} else {
// is not an email and isn't a number
}
function validateEmail(email) {
var 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(email);
}
This way you can check a little more thoroughly on what the input actually is, rather than just guessing it's one or the other.
I want to filter multiple zip codes in an input, there should be at least 2 zip SEPARATED by a COMA, I am trying to validate them in javascript with the following code but it's now filtering, the submit send the form to the next page without error, anyone can help?
<script>
function validateMULTIZIP() {
if(!/\d{11,}/.test(document.zipad.textfield.value) && document.getElementById('single').checked==false))
{
alert( "There should be a least two Zip codes separated by a coma." );
document.zipad.textfield.focus() ;
return false;
}
return true;
}
</script>
This will check for two 5-digit numbers separated by a comma
^\d{5},\d{5}$
But, you said at least two, so that means it needs to be a little more flexible to accommodate more. If the user enters 12345,12345,12345 it needs to be valid.
^\d{5}(?:,\d{5})+$
What if the user adds a space after the comma? Such as 12345, 12345. This is perfectly valid, so let's make sure our validator allows that.
^\d{5}(?:,\s*\d{5})+$
Oh, and zip codes can have an optional -1234 ending on them, too (known as ZIP+4. Maybe you want something like this
^\d{5}(?:-\d{4})?(?:,\s*\d{5}(?:-\d{4})?)+$
Now strings like this would be valid
12345
12345, 12345,12345
12345, 12345-9999, 12345
As a bonus, let's say 12345, 12345 is invalid because it has the same zip code twice. Here's how we'd fix that
(?:(\d{5}),?)(?!.*\1)
And here's the ZIP+4 version
(?:(\d{5}(?:-\d{4})?),?)(?!.*\1(?!-))
This one has a little added complexity because of possibility of (e.g.,) 12345, 12345-9999. This is valid but because 12345 can appear more than once, it makes sure that a 5-digit zip code can't be invalidated by a unique 9-digit zip code.
Note these duplicate-checking regexps do not enforce the minimum of two unique zip codes. If you want to check for duplicates you'd need to combine the two.
var valid5DigitZipCodes = function(str) {
if (! /^\d{5}(?:,\s*\d{5})+$/.test(str)) {
alert("You need at least 2 zip codes");
return false;
}
else if (! /(?:(\d{5}),?)(?!.*\1)/.test(str)) {
alert("You entered a duplicate zip code");
return false;
}
return true;
};
And here's the ZIP+4 variant if you want to support that
var valid9DigitZipCodes = function(str) {
if (! /^\d{5}(?:-\d{4})?(?:,\s*\d{5}(?:-\d{4})?)+$/.test(str)) {
alert("You need at least 2 zip codes");
return false;
}
else if (! /(?:(\d{5}(?:-\d{4})?),?)(?!.*\1(?!-)).test(str) {
alert("You entered a duplicate zip code");
return false;
}
return true;
};
Assuming (from your code) that ZIP code contains five digits and no other characters, you could use:
/\d{5},\d{5}/.test(document.zipad.textfield.value)
You regex: \d{11,} means "any digit, eleven times or more", that's why it's broken.
Another Solution without using regex would be splitting zip Codes by comma then check for the size of the resulting array.
Sample code:
<input type="text" id="in"></input>
<button onclick="validate()">Click</button>
JS
function validate() {
var inp = document.getElementById("in");
var content = inp.value;
var correct = validateZipString(content);
if (correct) {
alert("ok");
} else {
alert("not ok");
}
}
function validateZipString(zipString) {
var zipCodes = zipString.split(',');
if (zipCodes.length < 2) return false;
for (var i = 0; i < zipCodes.length; i++) {
//validate each zipCode if required
}
return true;
}
here is a working jsfiddle http://jsfiddle.net/VcNd9/3/
For anyone else interested in the variant that also matches 1 zip or more rather than two or more. Simply change the + quantifier for * at the end of the expression.
From:
^\d{5}(?:-\d{4})?(?:,\s*\d{5}(?:-\d{4})?)+$
To:
^\d{5}(?:-\d{4})?(?:,\s*\d{5}(?:-\d{4})?)*$
For example:
<input type="text" inputmode="numeric" pattern="^\d{5}(?:-\d{4})?(?:,\s*\d{5}(?:-\d{4})?)*$">
I'm trying to make a javascript function with a regex, that will validate a phone number.
the rules are :
1. numbers only.
2. more then 10 numbers.
3. a dash ( - ) is allowed (optional).
first, I tried this one :
function validatePhone(phone) {
var phoneReg = /[0-9]{10,}/;
return (phoneReg.test(phone));
}
it worked well only on the first 2 rules, but not with the dash.
Then I tried var phoneReg = /[-0-9]{10,}/; and even var phoneReg = [\d]+\-?[\d]+ but then the javascript was broken...
any thoughts ?
This is how I would approach phone number validation:
var validatePhone = function(phone) {
// Stip everything but the digits.
// People like to format phone numbers in all
// sorts of ways so we shouldn't complain
// about any of the formatting, just ensure the
// right number of digits exist.
phone = phone.replace(/\D/g, '');
// They should have entered 10-14 digits.
// 10 digits would be sans-country code,
// 14 would be the longest possible country code of 4 digits.
// Return `false` if the digit range isn't met.
if (!phone.match(/\d{10,14}/)) return false;
// If they entered 10, they have left out the country code.
// For this example we'll assume the US code of '1'.
if (phone.length === 10) phone = '1' + phone;
// This is a valid number, return the stripped number
// for reformatting and/or database storage.
return phone;
}
This should work. The - character needs to be escaped.
var phoneReg = /[0-9-\-]{11,}/;
The potential problem with this, is that strings that have multiple dashes will test positive even when 10 numbers aren't in the string. I would suggest replacing dashes before testing.
var phoneReg = /[0-9]{11,}/;
return (phoneReg.test(phone.replace(/\-/g, ''));