Validate (Australian) Phone Numbers in Javascript - 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

Related

How to perform string methods on function parameter in javascript

I am trying to write some javascript code to validate an HTML form and I am stuck. I am suspecting there are multiple issues (I am really new to JS) but the one I am stuck at is preventing me from further troubleshooting. Essentially, I need to have 2 functions, validatePassword and validateForm, one to validate the password and another to validate the rest of the input. The password needs to have an uppercase letter and be at least 8 characters long.
My main problem right now is that I do not know how to convert validatePassword's parameter to a string to check its length and whether it has an uppercase letter or not.
(Please let me know if you see any other problems with my code.)
Here it is:
// add validatePassword function here
function validatePassword(str) {
let value = String(str);
if (value.length < 8 && value !== value.toLowerCase()) {
return true;
}
return false;
}
const validateForm = (myForm) => {
// get text of fields
var firstname = myForm.firstname.value;
var lastname = myForm.lastname.value;
var password = myForm.password.value;
firstname != null
? true
: $("#message").html("Please enter a first name");
lastname != null
? true
: $("#message").html("Please enter a last name");
/* Form validation*/
validatePassword(password) == true
? true
: $("#message").html("Password incorrect");
return false; // prevent page reload
};
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
</head>
<body>
<form id="form1" action="#" onsubmit="return validateForm(this);">
first name: <input type="text" name="firstname" /><br />
last name: <input type="text" name="lastname" /><br />
password: <input type="text" name="password" /><br />
<button>Check</button>
</form>
<hr />
<div id="message"></div>
</body>
A few problems here:
There was a logic error in validatePassword (and some typos). You want the password to be invalid if the length is < 8 or the value is equal to its lowercase. Personally I would return true is the password was valid, but to each their own.
It is more conventional to use if statements instead of the ternary operator if you don't need its return value.
You need to reset the error message string if nothing is wrong in the form (this can be done before checking any of the fields).
// add validatePassword function here
function validatePassword(str) {
let value = String(str);
if (value.length < 8 || value === value.toLowerCase()) {
return true; // invalid password
}
return false; // valid password
}
const validateForm = (myForm) => {
// get text of fields
var firstname = myForm.firstname.value;
var lastname = myForm.lastname.value;
var password = myForm.password.value;
$("#message").html("");
if (!firstname) {
$("#message").html("Please enter a first name");
}
if (!lastname) {
$("#message").html("Please enter a last name");
}
/* Form validation*/
if (validatePassword(password) === true) {
$("#message").html("Password incorrect");
}
return false; // prevent page reload
};
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
</head>
<body>
<form id="form1" action="#" onsubmit="return validateForm(this);">
first name: <input type="text" name="firstname" /><br />
last name: <input type="text" name="lastname" /><br />
password: <input type="text" name="password" /><br />
<button>Check</button>
</form>
<hr />
<div id="message"></div>
</body>
Few observations/suggestions :
As password is always consider as a sensitive field, It should be a type of password instead of text. (No need to worry about the data type while getting it, You will get it as a string only)
As per the mentioned validation criteria for password The password needs to have an uppercase letter and be at least 8 characters long. Condition should be :
value.length <= 8 && value !== value.tolowerCase()
myForm.password.value will return a string only. Hence, No need to convert String into a String again.
Your final password validation function would be :
function validatePassword(value) {
return (value.length <= 8 && value !== value.tolowerCase()) ? true : false;
}

Create a guestbook application in HTML with some conditions in the input fields

I want to create a guestbook application page in HTML which has 3 fields for the user to input:
Name
E-mail
Message
I wanna make the client check in JavaScript, so below are my snippets of code which I added in the head of the html page.
For the Name I need to put a condition so only letters can be entered, no numbers, no special characters, no spaces or empty field, so I made this
function Validate()
{
var x=document.forms["guest"]["email"].value;
var y=document.forms["guest"]["name"].value;
var regex=/^[a-zA-Z]+$/;
if( y==null || y=="" || (!y.match(regex)))
{
alert("Please enter your Name! ");
return false;
}
My question is: How can I insert a condition so the name must be bigger than 3 letters?
For the e-mail field I made this:
if(x==null || x=="")
{
alert("Please enter your email address!");
return false;
}
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
else
return true;
}
Here I don`t have any question.
For the message field I need to add a condition so the message must be bigger than 10 characters.
Can you help me with that?
Thanks
You really dont even need javascript for this:
<form action="">
<input type="email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" name="email" required title="Valid email required" required>
<br>
<input type="text" pattern="[a-zA-Z]{3,}" name="name" required title="Letters only and at least 4 characters" required>
<br>
<input type="text" pattern=".{10,}" name="message" required title="10 characters minimum" required>
<br>
<button>Submit</button>
</form>
You should take a look into the length property.
E.g.:
var y=document.forms["guest"]["name"].value;
if(y.length < 3) {
alert("Not a valid name");
return false;
}
Further informations for the length property on w3schools
An other option is to use the HTML5 minlength attribute:
<label>Username: <input name=u required minlength=3></label>
Further informations for the minlength attribute on W3

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

Phone Number Javascript Validation

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.

JavaScript data validation

Please help me. The validation is not working:
<script type="text/javascript" src="javascript.js">
function validation()
{
var fname=document.forms["form1"]["fname"].value;
var lname=document.forms["form1"]["lname"].value;
var idnumber=document.forms["form1"]["idnumber"].value;
var email=document.forms["form1"]["email"].value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
var address=document.forms["form1"]["address"].value;
var phonenumber=document.forms["form1"]["phonenumber"].value;
if (fname==null || fname=="")
{
alert("Name should be entered correctly");
return false;
}
if (lname==null || lname=="")
{
alert("Name should be entered correctly");
return false;
}
if (isNaN(idnumber))
{
alert("Please enter a valid id number");
return false;
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid e-mail address");
return false;
}
if(address==null || address=="")
{
alert("Please insert your address");
return false;
}
if (isNaN(phonenumber))
{
alert("Please enter a valid phone number");
return false;
}
}
</script>
<form name="form1" action="validation.php" method="post" onsubmit=" return validation(this);return false">
Firstname:<input type="text" name="fname"><br/>
Lastname:<input type="text" name="lname"><br/>
Nation ID Number:<input type="text" name="idnumber" minlength="8"maxlength="8"><br/>
Email address: <input type="text" name="email"><br/>
Address:<input type="text" name="address"><br/>
Pnone number:<input type="text" name="phonenumber"><br/>
<input type="reset" name="reset" value="reset">
<input type="submit" name="submit" value="submit">
</form>
There are a number of issues with that code:
You really should not use the same <script> element for both calling src="javascript.js" and at the same time declare a function. Use separate elements, like this:
<script type="text/javascript" src="javascript.js"></script>
<script type="text/javascript">
function validation()
{
...
}
</script>
In the <form> element, there's a redundant ;return false. The form will take the value from return validation(this), anything after it will be ignored. Also, no need of ";" when using in-line javascript.
You are passing passing this as argument to the validation() function, but validation is expecting no argument. Should be:
function validation(oForm)
If you are already passing this, why not use it? this is a reference to the element itself, so it is, for the validation function, a reference to the form. So no need to name the form.
<form action="validation.php" method="post" onsubmit="return validation(this)">
And the references in function would be:
function validation(oForm)
{
var fname=oForm["fname"].value;
var lname=oForm["lname"].value;
}
Those changes alone could solve your problem. I'll check the code further to see if there is something else.
EDIT:
I've tested the validation now, and it works. The only required modification is removing the scr=validation.js from your <SCRIPT> tag. Use separate tags for that, as i suggested.
But i strongly suggest you consider the other issues I've mentioned.
Also, other suggestions regarding the validation itself:
For alphanumerical fields, no need to check for null, only "" is enough. You can simply use:
if (lname=="")
First Name and Last Name error messages are the same. That will confuse users.
Avoid testing phone numbers as numeric. Remember "(407) 234-5678" is a perfectly valid phone number, although it will fail your test. Unless you have a strong reason to treat it as numeric (automatic dialing?), leave it as an ordinary, text field.
In the National ID field: There is no minlength in HTML. Only maxlength
isNaN(idnumber) will return true if value is blank. And also if length<8. I assume it is a required field with a required length, so you should use:
if (isNaN(idnumber) || idnumber.length != 8)
{
alert("Please enter a valid id number");
return false;
}
For all your tests, consider trimming the values. Currently, input like " " (blanks only) WILL pass your test. Javascript has no built-in trim function, but it can be done with this:
function trim( texto ) {
return texto.replace(/^\s*|\s*$/g, "");
}
And used like this:
var fname=trim(oForm["fname"].value);
For clarity, use an explicit return true; in validation() after all tests successful.
Here is the suggested code after all changes:
<script type="text/javascript" scr="validation.js"></script>
<script type="text/javascript">
function validation(oForm)
{
var fname = trim(oForm["fname"].value);
var lname = trim(oForm["lname"].value);
var idnumber = trim(oForm["idnumber"].value);
var email = trim(oForm["email"].value);
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
var address = trim(oForm["address"].value);
var phonenumber = trim(oForm["phonenumber"].value);
if (fname=="")
{
alert("First name should be entered");
return false;
}
if (lname=="")
{
alert("Last name should be entered");
return false;
}
if (isNaN(idnumber) || idnumber.length != 8)
{
alert("Please enter a valid id number");
return false;
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid e-mail address");
return false;
}
if(address=="")
{
alert("Please insert your address");
return false;
}
if (isNaN(phonenumber))
{
alert("Please enter a valid phone number");
return false;
}
return true;
}
function trim( texto ) {
return texto.replace(/^\s*|\s*$/g, "");
}
</script>
<form name="form1" action="validation.php" method="post" onsubmit="return validation(this)">
Firstname:<input type="text" name="fname"><br/>
Lastname:<input type="text" name="lname"><br/>
Nation ID Number:<input type="text" name="idnumber" maxlength="8"><br/>
Email address: <input type="text" name="email"><br/>
Address:<input type="text" name="address"><br/>
Pnone number:<input type="text" name="phonenumber"><br/>
<input type="reset" name="reset" value="reset">
<input type="submit" name="submit" value="submit">
</form>

Categories

Resources