jQuery Validating Australian Phone Numbers - javascript

I am trying to get the value from an input box, validate & format the number, then update the input field.
I want it to validate all Australian phone numbers (mobile and landline)
formatting mobile numbers to
04XX XXX XXX
and Landline numbers to
(0X) XXXX XXXX
var phone_number = $("#phone").val();
//validate mobile number
var formatted = phone_number.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
//replace number
$("#phone").val(formatted);
Any help would be awesome :)

You can use the same regex/replace logic you have suggested.
html
Mobile:<input id = "mobile" type = "tel" maxlength=8></input>
Landline:<input id = "landline" type = "tel" maxlength=10></input>
jquery
$("#mobile").blur(function(){
var mobile_ele = $("#mobile");
var mobileNum = mobile_ele.val();
var formattedNum = mobileNum.replace(/(\d{2})(\d{3})(\d{3})/g,"04$1 $2 $3");
mobile_ele.val(formattedNum);
});
$("#landline").blur(function(){
var landline_ele = $("#landline");
var landlineNum = mobile_ele.val();
var formattedNum = landlineNum.replace(/(\d{2})(\d{4})(\d{4})/g,"($1) $2 $3");
mobile_ele.val(formattedNum);
});
Demo:https://jsfiddle.net/7c0d418t/

I came up with 1 solution, not convinced how optimal it is, but someone may want to elaborate on it.
function validatePhoneNumber(phone_number){
var formatted = "";
//remove all non-digits
phone_number = phone_number.replace(/\D/g,'');
//if number starts with 61, replace 61 with 0
if (phone_number.match(/^61/)){
phone_number = "0"+phone_number.slice(2);
}
if (phone_number.match(/^04/)){
if (phone_number.length === 10){
var formatted = phone_number.replace(/(\d{4})(\d{3})(\d{3})/g,"$1 $2 $3");
} else {
alert('Invalid phone number');
}
} else if (phone_number.match(/^02|03|07|08/)){
if (phone_number.length === 10) {
var formatted = phone_number.replace(/(\d{2})(\d{4})(\d{4})/g,"($1) $2 $3");
} else {
alert('Invalid phone number');
}
} else if (phone_number.length === 8){
alert('Please use Area Code for landline numbers');
} else {
alert('Invalid phone number');
}
//update
$("#phone").val(formatted);
}
DEMO: https://jsfiddle.net/kb4u536a/

You can find here phone validation code for more than 200 countries: https://github.com/googlei18n/libphonenumber

Related

How do I format input phone number without plugin in jQuery?

I want to format my <input id="phone_number" type="tel"> on keypress
The requirements of my input field are:
numbers only and no letters and other special characters
format the input field with a US number like (123) 457-7890
This is my current code:
jQuery("#phone_number").on("keypress", function(event) {
var reg = /[0-9]/g;
var key = String.fromCharCode(event.keyCode);
if(!reg.test(key)){
// return false if NOT number
return false;
} else {
// numbers only
var phone_value = jQuery("#phone_number").val();
var number = phone_value.replace(/(\d{3})(\d{3})(\d{2})/,"$1-$2-$3");
jQuery("#phone_number").val(number);
}
});
Problem: The problem with my code is that it is not able to limit length of my input
Final Output should look like (123) 457-7890 first 3 digits enclosed in a parentheses
Any help is greatly appreciated. Thanks
I guess this should give you what is needed. You were very close to the answer.
I have limited the length of <input> using the maxlength attribute and added parenthesis in your phone_value.replace() function surrounding $1.
jQuery("#phone_number").on("keypress", function(event) {
var reg = /[0-9]/g;
var key = String.fromCharCode(event.keyCode);
if(!reg.test(key)){
// return false if NOT number
return false;
} else {
// numbers only
var phone_value = jQuery("#phone_number").val();
var number = phone_value.replace(/(\d{3})(\d{3})(\d{2})/,"($1) $2-$3");
jQuery("#phone_number").val(number);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="phone_number" type="tel" maxlength="14">

Regex to replace non-numeric characters and insert dashes for phone number as it is typed

I need javascript to format a telephone number as it is typed. This would replace all non-numeric characters and insert dashes if the user doesn't type them in. So far this is the closest I've gotten, but it is thrown off if they put a dash in the wrong spot. The ideal solution would be to replace dashes only in the wrong spots. I was looking for a way to possibly replace the 4th and the 8th digit differently but haven't come up with a solution.
$('#TelephoneNo').keyup(function (ev) {
if (/[^0-9\-]/g.test(this.value))
{
this.value = this.value.replace(/[^0-9\-]/g, '');
}
if (/^(\d{3})(\d)/.test(this.value))
{
this.value = this.value.replace(/^(\d{3})(\d)/, '$1-$2');
}
if (/^(\d{3}-\d{3})(\d)/.test(this.value))
{
this.value = this.value.replace(/^(\d{3}-\d{3})(\d)/, '$1-$2');
}
});
Assuming you want the format "123-456-7890":
function formatPhoneNumber(s) {
var s2 = (""+s).replace(/\D/g, '');
var m = s2.match(/^(\d{3})(\d{3})(\d{4})$/);
return (!m) ? null : m[1] + " -" + m[2] + "-" + m[3];
}
<html>
<head>
<script type="text/javascript">
function CheckNum(ev) {
var inputval=document.getElementById("TelephoneNo").value;
debugger
if(inputval){
if (/[^0-9\-]/g.test(inputval))
{
inputval = inputval.replace(/[^0-9\-]/g, '');
}
if(detectPosition()){
if (/^(\d{3})(\d)/.test(inputval))
{
inputval = inputval.replace(/^(\d{3})(\d)/, '$1-$2');
}
if (/^(\d{3}-\d{3})(\d)/.test(inputval))
{
inputval = inputval.replace(/^(\d{3}-\d{3})(\d)/, '$1-$2');
}
}
document.getElementById("TelephoneNo").value=inputval;
}
}
function detectPosition() { var inputval=document.getElementById("TelephoneNo").value;
if(inputval.indexOf("-") ==4 || inputval.indexOf("-") ==8)
{
return 1;
}
return -1;
}
</script>
</head>
<body>
<input type="text" id="TelephoneNo" onkeyup="CheckNum(this)">
</body>
</html>
I know this is an old question, but I figured I might help someone out.
I did this xxx-xxx-xxxx as-you-type formatting using two cases: one for formatting where the length required one hyphen, and another for formatting with two required. That way, the last group always expects an unknown char count and doesn't wait until the end of the user input to enforce the format.
function formatPhone() {
var element = document.getElementById('phone');
var inputValue = element.value;
// length < 3 : no formatting necessary
if (inputValue.length > 3 && inputValue.length < 8)
// length < 8 : only one hyphen necessary, after first group of 3
// replace (remove) non-digits, then format groups 1 and 2
result = inputValue.replace(/\D/gi, '').replace(/(.{3})(.{0,3})/g, '$1-$2');
else
// length >= 8 : 2 hyphens required, after first two groups of 3
// replace (remove) non-digits, then format groups 1, 2, and 3
result = inputValue.replace(/\D/gi, '').replace(/(.{3})(.{3})(.{0,4})/g, '$1-$2-$3');
element.value = result;
}
Type a phone number, it will be formatted to xxx-xxx-xxxx as you type:<br/><br/>
<input type="text" id="phone" maxlength="12" onkeyup="formatPhone()"></input>

Regex: Check if string contains SSN in any part of the string

Can any one tell how to check if a String contains a social security number (SSN) using REGEX
Example data:
(1): my ssn is 123-44-8686
validate this ==> Need to return as true, since it contains a number in SSN format (XXX-XX-XXXX)
(2) my ssn is nothing ==> Need to return as false, since it does not contain a number in SSN format
No need to use REGEX.
Hopefully Something like this will work
var str = "123-44-8686";
var res = str.split("-");
if(res.length == 3){
var ssn1=res[0];
if(ssn1.length==3){
var ssn2=res[1];
if(ssn2.length==2){
var ssn3=res[2];
if(ssn3.length==4){
alert("valid formate");
}
}
}
}
else{
alert('Invalid formate');
}

Validate user input for extra long words in textarea

I have a problem here with validating user's input in textarea.
A user is suppose to enter his description in one of the textarea feild in form. But some people just put the random text like 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' or something to bypass the minimum length requirement.
Now i want to prevent user from typing such long text without any spaces since it disrupts the UI of my page.
Also a long text entered by user without any spaces can be a valid url too. So how do i manage this & throw a error to user to correct the text only if it is too long and it isnt a valid url ??
PS: I dont want to split string myself.. I just want to detect it and throw error to user on client side validation. Just to put end to some doubts, i will do server side validation in which i will forcibly enter a space and save it in DB. But i am expecting to solve this problem on client side
var STRING_MAX_LENGTH = 10;
var description = 'aaa aaaaaaaaaa bbbbbbbbbb http://www.google.com/search?q=client-side-filtering';
var array = description.split( ' ' );
$.each( array, function() {
if ( this.length >= STRING_MAX_LENGTH ) {
if( /^([a-z]([a-z]|\d|\+|-|\.)*):(\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*#)?((\[(|(v[\da-f]{1,}\.(([a-z]|\d|-|\.|_|~)|[!\$&'\(\)\*\+,;=]|:)+))\])|((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=])*)(:\d*)?)(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)*)*|(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)*)*)?)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)*)*)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)){0})(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)|\/|\?)*)?$/i . test( this ) ) {
alert( this + ' is an URL' );
} else {
alert( this + ' is not an URL' );
}
}
});
http://jsfiddle.net/vVYAp/
function validate()
{
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var wordLengthExpr = /\b[^\s]{50,}\b/;
var regex = new RegExp(expression);
var wordLengthRegex = new RegExp(wordLengthExpr);
var t = $("#myTextarea").val();
if (t.match(regex) || !t.match(wordLengthRegex))
{
//valid
}
else
{
//throw error
}
}
This is a two step process:
Determine if any words are too long.
If so, determine if they are valid URLs.
var validateWordLength = function (str) {
var maxLength = 50, // or whatever max length you want
reURL = /^(ftp|http|https):\/\/[^\s]+$/, // use whatever regular expression for URL matching you feel best
words = str.split(/\s+/),
i;
for (i = 0; i < words.length; i += 1) {
if (words[i].length > maxLength) {
// test for url
// but bear in mind the answer at http://stackoverflow.com/questions/1410311/regular-expression-for-url-validation-in-javascript
// testing for url may not be fruitful
if (!reURL.test(words[i])) {
return false;
}
}
}
return true;
};
try this
var value = Your text;
var result = value.replace(" ","");
if(value.length == result .length)
//not valid
else
//valid
You can get length of each word, and then can decide whether to allow the user or not -
var arr = text.split(' ');
$.each(arr,function(){
console.log(this.length);
// check valid word length
});
http://jsfiddle.net/mohammadAdil/cNZtn/
If you use the jQuery validate plugin you can add a method to it:
jQuery.validator.addMethod("samechars", function(value, element) {
return this.optional(element) || !/([a-z\d])\1\1/i.test(value);
}, "Invalid input");
If you want to use jQuery you can use the following:
$("form").submit(function(e){
var $textarea = $('#msg'),
maxWordLength = 20;
var value = $textarea.val().split(' '),
longWord = false;
for(var n = 0; n < value.length; n++) {
if(value[n].length >= maxWordLength)
longWord = true;
}
if(longWord) {
alert('Too long word');
return false;
}
});
Here is a fiddle:
http://jsfiddle.net/pJgyu/31286/

Advanced Javascript form validation function

This is what I'm using.
It's great. I only need to add function that checks if one of "cp", "bp", "hp" input area is entered or not. If not it should give an error that says "Please enter at least 1 phone number."
(cp = cell phone, bp = business phone, hp = home phone)
function checkPhones(){
var frm = document.forms["myform"];
var cell = frm.cp.val;
var bus = frm.bp.val;
var home = frm.hp.val;
if(ValidatePhone(cell) || ValidatePhone(bus) || ValidatePhone(home)){
return true;
}
return false;
}
function ValidatePhone(val){
//insert code to check phone meets your system requirements
//either length or pattern
//return true or false
}
frmvalidator.setAddnlValidationFunction("checkPhones");

Categories

Resources