Phone Number Javascript Validation - javascript

Hello I am having trouble with my javascript validation. I am trying to validate a Phone number which I want it to display only numbers and single spaces.
My Javascript code:
<script type="text/javascript">
function validateForm()
{
var x=document.forms["checkout_details"]["phone"].value;
if (!isNaN(phone).value)//if the entered phone number is not a number
{
alert("Please enter a valid phone number");
ret = false;//return false, form is not submitted
}
}
</script>
HTML/PHP Code:
echo '<form name="checkout_details" action="confirm.php" onsubmit="return validateForm()" method="post">';
echo '<font color="red">*</font> <b>Phone Number:</b> <input type="text" name="phone" id="phone"><br /><br />';
echo '<input type="submit" value="Purchase">';
</form>
Anyone help me out tell me what i'm doing wrong. Thanks.

This is incorrect:
if (!isNaN(phone).value)//if the entered phone number is not a number
That actually evaluates to if it IS a number (double negative makes a positive). Also, ret = false; should be return false;
To remove spaces from the input before checking if it is valid, see this answer.

Try this
function validateForm()
{
var x=document.forms["checkout_details"]["phone"].value;
if (!isNaN(x))
{
alert("Please enter a valid phone number");
return false;
}
else
return true;
}

Your function needs to return true or false. A false return will prevent your form from posting.
So change this:
ret = false;//return false, form is not submitted
to:
return false;//return false, form is not submitted
Additionally, you cannot rely on isNaN to validate this field. In addition to not taking into account any phone numbers with spaces or other characters, it will not work correctly in some cases, and in this case you are negating its return value (!isNaN(x)), which means it won't work at all unless you fix that. You are better off using a regular expression to validate this field.

Related

How to validate if the input text (in html) is a valid Phone Number when user hits the 11th number?

I have an input.
<input id="phoneNumber"/>
How can I validate if the inserted value from user is a valid phone number or not using jQuery ?
Thanks.
You can use oninput to check if input has some values entered or not.
When 10th value is entered you can use a alert but this will not be enough because after alert, user can still enter more values. So use maxlength="10" to allow only 10 numbers.
Also if you don't want to allow text but numbers only than you can use .replace(/[^\d]/, '') to replace any non-number . And show that it is not a number.
function validPhone(phoneNum)
// check for valid phone numbers in the format 999-999-9999
{
if (phoneNum.value.match(/[^\d]/)) {
phoneNum.value = phoneNum.value.replace(/[^\d]/, '')
document.querySelector("#demo1").innerHTML = "Sorry numbers only";
} else {
document.querySelector("#demo1").innerHTML = "";
}
var strPhone = phoneNum.value;
var rePhone = /\d{3}-\d{3}-\d{4}/;
if (strPhone.length >= 10) {
phoneNum.select();
document.querySelector("#demo1").innerHTML ="No more numbers plz, only 10 digits allowed in Phone number.";
}
document.querySelector("#demo").innerHTML = strPhone.length;
};
#demo1 {
color: red;
}
<input class="form-control" oninput="validPhone(this)" type="text" name="username" placeholder="Enter Phone number" maxlength="10" id="phoneNumberForForgotPassword" data-val-required="نام کاربری را وارد نمائید.">
<div id="demo1"></div>
<div id="demo"></div>

Overall country telephone number validation in magento checkout page

overall country telephone number validation in magento checkout page
i add the regular expression for the telephone number validation.js in
js/prototype/validation.js
['validate-phoneStrict',
'Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.',
function(v)
{
return Validation.get('IsEmpty').test(v)
|| /\(?([0-9]{4})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/.test(v);
}
],
I need the regular expression for the overall countries ,....please help me
HTML code
<input type="text" name="telephone" id="telephone" value="<?php echo $this->htmlEscape($this->getFormData()->getTelephone()) ?>" title="<?php echo $this->__('Telephone') ?>" class="input-text validate-numeric-contact" />
js Code add below in billing.phtml
<script type="text/javascript">
//<![CDATA[
if(Validation) {
Validation.addAllThese([
['validate-numeric-contact','Enter correct mobile number',
function(v){
var timePat ="^((\+){0,1}91(\s){0,1}(\-){0,1}(\s){0,1}){0,1}9[0-9](\s){0,1}(\-){0,1}(\s){0,1}[1-9]{1}[0-9]{7}$";
// var matchArray = v.match(timePat);
if(v.length > 0){
if(v.length !=10){
return false;
}else if(v[0] != 9 || v[1] != 1 ){
//return false;
}else if(v[2]!=9 && v[2]!=8 && v[2]!=7){
return false;
}
return true;
}else {
return false;
}
}
]])};
var dataForm = new VarienForm('form-id', true);
//]]>
</script>
Please search on the website for related questions.
What regular expression will match valid international phone numbers? This contains the regex you need.
An example solution for you would be:
[ 'validate-phoneStrict',
'Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.',
function(v)
{
return Validation.get('IsEmpty').test(v)
|| /\+(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)\d{1,14}$/.test(v);
}
]
I used the accepted answer in the above question, without testing it myself. Please also read the last answer on that page for the caveats on this regex

Form only validates one field with javascript

I'm trying to make a simple register form that makes sure the username and password have been entered correctly before submitting. Here's my form:
<form id="register" name="register" action="" method="POST" onsubmit="return validate_account_creation(this)">
<label> Username
<input type="text" name="username" />
</label>
<label> Password
<input type="text" name="password" />
</label>
<input type="submit" name="submit" value="Submit" class="button"/>
</form>
And here are my javascript functions:
function validate_username(username) {
var regex = /[a-zA-Z0-9\-\_]{5,15}/g;
var str = username;
if (!regex.test(str)) {
alert("Your username must be between 5 and 15 characters in length");
register.username.focus();
return false;
}
}
function validate_password(password) {
regex = /[a-zA-Z]{5,}[0-9]{1,}/g;
str = password;
if (!regex.test(str)) {
alert("Your password must be at least 6 characters in length and must contain at least 1 number");
register.password.focus();
return false;
}
}
//Validate register form
function validate_account_creation(form) {
return validate_username(form.username.value);
return validate_password(form.password.value);
return true;
}
The username function works fine and it validates that one every time. However, if the username is correct, the form submits. The second function never activates. If the first function doesn't return anything, shouldn't the second function then be called and validate the second field?
It's the return statements. A return aborts the rest of the function and returns the result, so your validation should look like:
Javascript
function validate_account_creation(form) {
var username = validate_username(form.username.value);
var password = validate_password(form.password.value);
return username && password; // if both are true, submit form
}

Phone number validation problems

I have written some javascript to validate a phone number field if something is entered (it is an optional field) but it doesn't seem to be working, if i enter wrong values it still submits. Here is my code:
<script>
function validatePhone()
{
var num1 = document.getElementById('workno');
if (num1 !== null)
{
regex = /\(\d{2}\)\d{8}/;
}
if (!num1.match(regex))
{
alert('That is not a correct telephone number format');
return false;
}
}
</script>
<form name="eoiform" form method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi" onsubmit="return validatePhone();">
<input type="text" id="workno" name="workno">
<input type="submit" name="submit" id="submit" value="submit">
</form>
Can anyone spot my mistake?
Your num1 variable contains an element object, not its value so can't be tested with a regexp as it stands.
It will only ever by null if the element does not exist; it will be "" if its got no value.
function validatePhone()
{
var num1 = document.getElementById('workno').value;
if (num1 !== "" && !num1.match(/\(\d{2}\)\d{8}/))
{
alert('That is not a correct telephone number format');
return false;
}
}
You also have the invalid form method="POST" in your HTML.
Maybe you should select the value from the Input. Can you try
if (!num1.value.match(regex))
In addition to the problems noted in the other answers, you should also anchor the regexp. Otherwise, it will allow extra characters outside the phone number.
function validatePhone()
{
var num1 = document.getElementById('workno').value;
if (num1 !== "" && !num1.match(/^\(\d{2}\)\d{8}$/))
{
alert('That is not a correct telephone number format');
return false;
}
}

Validate (Australian) Phone Numbers in Javascript

I need to validate Australian phone numbers (e.g. 02[3-9]\d{7} or 07[3-9]\d{7} or 04[\d]{8}) in JavaScript.
Requirements:
must be 10 digits
no commas
no dashes
no + in front
must begin with 0
At the moment I can validate required fields and email address but I want to add phone number validation.
<html>
<head>
<script type="text/javascript">
function validateForm() {
var x=document.forms["form3"]["name"].value;
if (x==null || x=="") {
alert("Name must be filled out");
return false;
}
var s=document.forms["form3"]["phone"].value;
if (s==null || s=="") {
alert("Please Enter your Phone or Mobile Number - Preferably Phone Number");
return false;
}
var s=document.forms["form3"]["email"].value;
if (s==null || s=="") {
alert("Please Enter a valid email address");
return false;
}
var k=document.forms["form3"]["email"].value;
var atpos=k.indexOf("#");
var dotpos=k.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=k.length) {
alert("Email Address is Not Valid. Please provide your correct email address.");
return false;
}
}
</script>
</head>
<body>
<form action="/thank-you.php" name="form3" method="post" onsubmit="return validateForm();" >
Your name* <input type="text" name="name" />
Phone number* <input type="text" name="phone" />
Email* <input type="text" name="email" />
<input type="submit" value="sumbit" name="submit" class="button" onclick="javascript:return validateMyForm();" /><input type="reset" value="Reset" class="resetbutton" />
</form>
</body>
</html>
Can someone help out?
Here is a regex that I would recomment
var pattern = /^0[0-8]\d{8}$/g;
So input must start with 0, and followed by a digit and it must be one between 0-8. Then it must have 8 more digit numbers.
Valid phone number examples:
0010293999 (ok)
0110293999 (ok)
0210293999 (ok)
0910293999 (nope)
//Implementation
........
var phoneNumber =document.forms["form3"]["phone"].value;
var phonePattern = /^0[0-8]\d{8}$/g;
//phone number is not valid. Please notice that you don't need to check if it's empty or null since Regex checks it for you anyways
if (!phoneNumber.test(phonePattern))
{
alert("Please Enter your Phone or Mobile Number - Preferably Phone Number");
return false;
}
..........
---- Edit
........
var phoneNumber =document.forms["form3"]["phone"].value;
var phonePattern = /^0[0-8]\d{8}$/g;
//phone number is not valid. Please notice that you don't need to check if it's empty or null since Regex checks it for you anyways
if (!phonePattern.test(phoneNumber))
{
alert("Please Enter your Phone or Mobile Number - Preferably Phone Number");
return false;
}
..........
Thanks to Paul Ferrett for this (php not js, but the regex should translate):
<?php
function validate_phone($number) {
$number = preg_replace('/[^\d]/', '', $number);
return preg_match('/^(0(2|3|4|7|8))?\d{8}$/', $number)
|| preg_match('/^1(3|8)00\d{6}$/', $number)
|| preg_match('/^13\d{4}$/', $number);
}
NB: "MIT License"
Take a look at the Javascript RegExp Object and RegExp test() method.
var patt = /04[\d]{8}/g; // Shorthand for RegExp object
var phoneNumber1 = '0412345678';
var result1 = patt.test(phoneNumber1); // result1 is true
var phoneNumber2 = 'abc';
var result2 = patt.test(phoneNumber2); // result2 is false
You can also use the required pattern.
I've never used it before but it looks like this:
<input type="text"
id="phoneNumber"
title="Phone numbers must be 10 digits and start with 0."
required pattern="0[::digit::]{10}"
/>
// It's late, no idea if that's a valid regex or if works with POSIX.
See this html5rocks article for more info:
http://www.html5rocks.com/en/tutorials/forms/html5forms/#toc-validation
Here is a more robust Australian phone regex. Courtesy of this SO question.
let phonePattern = /^(?:\+?(61))? ?(?:\((?=.*\)))?(0?[2-57-8])\)? ?(\d\d(?:[- ](?=\d{3})|(?!\d\d[- ]?\d[- ]))\d\d[- ]?\d[- ]?\d{3})$/
Testing:
0412123123 TRUE
0491579999 TRUE
0491572983 TRUE
0712122123 TRUE
0212122123 TRUE
0000000000 FALSE
5555551234 FALSE
04121231231 FALSE
041212312 FALSE

Categories

Resources