Phone Number Validation With Spacing - javascript

I have researched all over the place for a phone number validation in JavaScript that adds spacing as they type.
The closest code I came to was
$('#ssn').keyup(function() {
var val = this.value.replace(/\D/g, '');
var newVal = '';
while (val.length > 3) {
newVal += val.substr(0, 3) + '-';
val = val.substr(3);
}
newVal += val;
this.value = newVal;
});
http://jsfiddle.net/ssthil/nY2QT/.
Expect that is American Mobile Numbers. Anyone know how to do Australia format (XXXX XXX XXX). I tried moving the digits around in the JavaScript but nothing seemed to work.

Try this code :
while (val.length > 3) {
if(newVal.length > 4){
newVal += val.substr(0, 3) + ' ';
val = val.substr(3);
} else {
newVal += val.substr(0, 4) + ' ';
val = val.substr(4);
}
}
newVal += val;
this.value = newVal;
});
Working fiddle :
http://jsfiddle.net/nY2QT/718/

Modifying your code a little bit you can get something like this:
$('#ssn').on('input', function() {
var val = this.value.replace(/\D/g, '');
if(val.length > 10) {
this.value = this.value.slice(0,12);
} else {
this.value = (val.slice(0,4) + ' ' + val.slice(4,7) + ' ' + val.slice(7,10)).trim();
}
});

I have made some changes with loop hope it will works
$('#ssn').keyup(function() {
var val = this.value.replace(/\D/g, '');
var newVal = '';
var flag = true;
while (val.length > 3) {
if(flag){
flag=false;
newVal += val.substr(0, 4) + '-';
val = val.substr(4);
} else {
newVal += val.substr(0, 3) + '-';
val = val.substr(3);
}
}
newVal += val;
if(this.value.length >= 5){
this.value = newVal;
}
});

You could have instead three <input /> elements, give them each maxlength="4", maxlength="3", and maxlength="3" respectively. And as soon as the user completes each input, they're moved to the following:
HTML
<form>
<input maxlength="4" autofocus="autofocus" name="first"/>
-
<input maxlength="3" name="second"/>
-
<input maxlength="3" name="third"/>
</form>
Javascript/jQuery
// Autofocus second after first is complete
$('[name="first"]').keyup(function() {
if ( $(this).val().length == 4) {
$('[name="second"]').focus();
}
});
// Autofocus third after second is complete
$('[name="second"]').keyup(function() {
if ( $(this).val().length == 3) {
$('[name="third"]').focus();
}
});
// Alert numer after third is complete
$('[name="third"]').keyup(function() {
if ( $(this).val().length == 3) {
alert("Number: " + $('[name="first"]').val() + "-" + $('[name="second"]').val() + "-" + $('[name="third"]').val() + ".");
}
});
Also, to valide for only numbers, you can use RegEx:
// The following code is RegEx, used to validate the inputs so that the user can only type in numbers
$('[name="first"], [name="second"], [name="third"]').on('input', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
// Support for old browsers
$('[name="first"], [name="second"], [name="third"]').on('keyup', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
Eureka!
Edit: answer to Z-Dog's "question":
// Autofocus first if backspace is pressed and this is empty
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '8' && $(this).val().length == 0){
$('[name="first"]').focus();
// And delete last character
$('[name="first"]').val(
function(index, value){
return value.substr(0, value.length - 1);
});
return false;
}
Eureka 2.0!

Use Jquery Mask plug-in
https://igorescobar.github.io/jQuery-Mask-Plugin/
It simple to integrate ans use

Use this code it might work
document.getElementById('ssn').addEventListener('input', function (e) {
e.target.value = e.target.value.replace(/(\d{4}) ?(\d{3}) ?(\d{3})/,
'$1 $2 $3');
});

Related

I want to display social security number like this xxx-xx-**** last four digits we have to hide while entering the key

jQuery code
$('#ssn1').keyup(function() {
var val = this.value.replace(/\D/g, '');
var newVal = '';
if(val.length > 4) {
this.value = val;
}
if((val.length > 3) && (val.length < 6)) {
newVal += val.substr(0, 3) + '-';
val = val.substr(3);
}
if (val.length > 5) {
newVal += val.substr(0, 3) + '-';
newVal += val.substr(3, 2) + '-';
val = val.substr(5);
}
newVal += val;
this.value = newVal.substring(0, 11);
});
Please help me how to hide last four digits and store in database like password,Please give me some edit for this code.Thanks in Advance.but retain the value in the field.

How to simulate back tab in textarea

I'm trying to simulate tabbing in a textarea, so far tab forward works but I'm not quite sure how to make backtab work. Any suggestions on how to do this, or better ways to do it would be helpful.
$('textarea').on('keydown mousedown', function(e){
var val = this.value,
start = this.selectionStart,
end = this.selectionEnd;
if (e.shiftKey) {
console.log('shift')
if (e.which == 9 || e.keyCode == 9) {
console.log('shift + tab')
e.preventDefault();
this.value = val.substring(0, start) + '\t' + val.substring(end);
}
} else if (e.which == 9 || e.keyCode == 9) {
console.log('tab')
e.preventDefault();
this.value = val.substring(0, start) + '\t' + val.substring(end);
}
})
This might get you started.
$('textarea').on('keydown mousedown', function(e) {
var val = this.value,
start = this.selectionStart,
end = this.selectionEnd;
if (e.which == 9 || e.keyCode == 9) {
e.preventDefault();
if (e.shiftKey) {
var firstTabPoint = val.lastIndexOf('\n', start) + 1;
if (val.substring(firstTabPoint, firstTabPoint + 1) == '\t') {
var startString = val.substr(0, firstTabPoint);
var endString = val.substr(firstTabPoint + 1);
this.value = startString + endString;
this.setSelectionRange(start - 1, end - 1);
}
} else {
this.value = val.substring(0, start) + '\t' + val.substring(end);
this.setSelectionRange(start + 1, end + 1);
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows="20" cols="100">
Add some lines in here, tab them, and then try untabbing.
</textarea>
As a side note, you might look into the attribute contenteditable="true" if you are making a text editor application.

How to do date masking using javascript (without JQuery)?

<![CDATA[
var $ = jQuery;
String locale = getUserLocale();
$(document).ready(function() {
if (!isEmptyNull(locale) && locale.equals("zh_CN")) {
$("input[id*='text12']").mask('9999年99月99日');
}
else {
$("input[id*='text12']").mask('99/99/9999');
}
});
]]>
<p:calendar id="text12" styleClass="calendar" maxlength="10" pattern="#
{pc_Test.dateDisplayFormat}"></p:calendar>
If the locale is equal to 'zh_CN', the masking would be '9999年99月99日'. Otherwise, it would would be '99/99/9999'.
When I remove the if else command, it works. But if I put the if else command inside, it doesn't work.
How do I solve it?
Check out the below code..
<input
type="text"
name="date"
placeholder="dd/mm/yyyy"
onkeyup="
var v = this.value;
if (v.match(/^\d{2}$/) !== null) {
this.value = v + '/';
} else if (v.match(/^\d{2}\/\d{2}$/) !== null) {
this.value = v + '/';
}"
maxlength="10"
>
<input
type="text"
name="date"
placeholder="mm/dd/yyyy"
onkeyup="
var v = this.value;
if (v.match(/^\d{2}$/) !== null) {
this.value = v + '/';
} else if (v.match(/^\d{2}\/\d{2}$/) !== null) {
this.value = v + '/';
}"
maxlength="10"
>
<input
type="text"
name="date"
placeholder="yyyy/mm/dd"
onkeyup="
var v = this.value;
if (v.match(/^\d{4}$/) !== null) {
this.value = v + '/';
} else if (v.match(/^\d{4}\/\d{2}$/) !== null) {
this.value = v + '/';
}"
maxlength="10"
>
<input
type="text"
name="date"
placeholder="yyyy年mm月dd"
onkeyup="
var v = this.value;
if (v.match(/^\d{4}$/) !== null) {
this.value = v + '年';
} else if (v.match(/^\d{4}年\d{2}$/) !== null) {
this.value = v + '月';
}"
maxlength="10"
>
Hope this is what you are looking for!
I had some trouble getting the currently accepted answers to work properly while retaining the ability to backspace. This was my solution. It retains backspacing and also doesn't show the slash until the number following it is typed.
const maskDate = value => {
let v = value.replace(/\D/g,'').slice(0, 10);
if (v.length >= 5) {
return `${v.slice(0,2)}/${v.slice(2,4)}/${v.slice(4)}`;
}
else if (v.length >= 3) {
return `${v.slice(0,2)}/${v.slice(2)}`;
}
return v
}
I've also create a github gist for this snippet here.
I have solved this issue a simple function(without regular expressions and only for the format 'dd/mm/yyyy'). And the important thing is that My function pays attention to the maximum values of the date(31) and month(12). For example, You can not input 32/11/2000 or 20/13/2000.
function maskForDate(value) {
if (value.length > 10) {
return value.substring(0, 10);
}
switch (value.length) {
case 1:
if (value > 3) {
value = "3";
}
break;
case 2:
if (value > 31) {
value = "31";
}
break;
case 3:
case 4:
if (value[2] !== "/") {
value = value.substr(0, 2) + "/" + value[2];
}
if (value[3] > 1) {
value = value.substr(0, 3) + "1";
}
break;
case 5:
if (value.substr(3, 2) > 12) {
value = value.substr(0, 3) + "12";
}
break;
case 6:
case 7:
if (value[5] !== "/") {
value = value.substr(0, 5) + "/" + value[5];
}
if (value[6] < 1) {
value = value.substr(0, 6) + "1";
}
break;
default:
break;
}
return value;
}
Try out this code, this will format your date in mm/dd/yyyy format as you type it in the input box.
Create an onchange event on the input box and call the date_formator function with the input date.
function date_formator(date) {
date = date.replace('//', '/');
var result = date.split("/");
var length = result.length;
// Append "/" after the last two charas, if more than 2 charas then remove it
if (length <= 2 && result[length - 1] != "") {
var last_two_digits = result[length -1];
if (last_two_digits.length >= 2) {
date = date.slice(0, -last_two_digits.length);
date = date + last_two_digits.slice(0,2) + "/";
}
}
if (typeof result[2] != "undefined") {
var year = result[2];
if (year.length > 4) {
date = date.slice(0, -year.length);
year = year.slice(0, 4);
date = date + year;
}
}
return date;
}
This works quite well (tried it in console on the jquery mask page)
if (locale !=='' && locale==='zh_CN') {
$('#text12').mask('9999年99月99日');
}
else {
$('#text12').mask('99/99/9999');
}
but if you want the mask format to show up in the input field you need to pass it as placeholder attribute
$('#text12').attr('placeholder', '9999年99月99日')
hope this helps

Format a number to time like hh:mm

I have an iput field:
<input type="text" name="time" class="time" value="3" />
I need that value to be like 03:00
More examples of what I need:
1 = 01:00
12 = 12:00
12:2 = 12:20
2:2 = 02:20
02:2 = 02:20
340 = 340:00
340:1 = 340:10
You know the rest. How can I solve this in jquery/javascript?
This is what I try in jQuery:
$('input').blur(timeFormat);
function timeFormat(e){
skjema.find('input.tid').each(function(){
if($(this).val().length != 0){
var tid = $(this).val().toString();
if(tid.length == 1){
$(this).val(String("0" + tid));
}
if(tid.indexOf(':') == -1){
$(this).val(tid.toString() + ':00');
}
}
});
}
This is what I have made now and it does the job, but it is somewhat bulky :)
function timeFormat(e){
skjema.find('input.tid').each(function(){
if($(this).val().length != 0){
var tid = $(this).val().toString();
tid = (tid.length == 1) ? '0' + tid : tid;
tid = (tid.indexOf(':') == -1) ? tid + ':00' : tid;
if(tid.indexOf(':') != -1){
var arr = tid.split(':');
var before = arr[0].toString();
var after = arr[1].toString();
before = (before.length == 0) ? '00' : before;
before = (before.length == 1) ? '0' + before : before;
after = (after.length == 0) ? '00' : after;
after = (after.length == 1) ? after + '0' : after;
console.log('before: ' + before + ' After: ' + after);
tid = before + ':' + after;
}
}
$(this).val(tid);
});
}
You can do this with some simple regex:
function time( str ) {
if ( !/:/.test( str ) ) { str += ':00'; }
return str.replace(/^\d{1}:/, '0$&').replace(/:\d{1}$/, '$&0' );
}
If you want to make sure only the expected format is accepted, add this line at the top of the function:
if ( /[^:\d]/.test( str ) ) { return false; }
Demo: http://jsfiddle.net/elclanrs/MzgMz/
YOu can try something like this using datejs library:-
var dateString = "12";
var date = new Date.parseExact(dateString, "hh:mm");
check this DEMO
$('input').blur(timeFormat);
function timeFormat(e){
$("div").find('input').each(function(){
if($(this).val().length != 0){
var tid = $(this).val().toString();
if(tid.length == 1){
$(this).val(String("0" + tid));
}
if(tid.indexOf(':') == -1){
$(this).val(tid.toString() + ':00');
}
if(tid.indexOf(':') == 2){
$(this).val(tid.toString() + '0');
}
}
});
}​
<title>Insert Colon in the Time Format</title>
<script type="text/javascript">
function formatTime(objFormField){
intFieldLength = objFormField.value.length;
if(intFieldLength==2 || intFieldLength == 2){
objFormField.value = objFormField.value + ":";
return false;
}
}
</script>
Enter time <input type="text" maxlength="5" minlength="5" onKeyPress="formatTime(this)"/>
Pseudo:
val ← value from field ($('.time').val())
colonPos ← position of . in val
If colonPos equals -1, result ← padZero(val) + ':00'
Else, result ← padZero(val[:colonPos]) + ':' + padZero(val[colonPos + 1:])
function prettyTime(t){
// will output a time providing leading zeros and minute field
// (doesn't need jQuery)
x=t.split(":");
for (var i=0; i<2; i++)
x[i] = (x[i]) ? Array(3-x[i].length).join('0') + x[i] : '00';
return x.join(":");
}
// --
$('input').blur(timeFormat);
function timeFormat(e){
skjema.find('input.tid').each(function(){
$(this).val(function(i, v) { return prettyTime(v); })
});
}
Maybe u can try this plugin.. Worked for me
Usage Examples:
$("#tbPlain").timefield();
$("#tb12Hour").timefield({ 'hourFormat': '12'});
$("#tb24Hour").timefield({ 'hourFormat': '24'});
$("#tbWithInvalidHandler").timefield({
'hourFormat': '24',
'onError' : function(){
alert(this.value+' is not a valid time!');
this.style.backgroundColor='red';
}
});
$("#tbOnOff").timefield();
$("#btnTurnOff").click(function(){
$("#tbOnOff").timefield('turnOffTimeField');
});
Live Example:
https://jsfiddle.net/sajjansarkar/bst3cw2g/

Phone mask with jQuery and Masked Input Plugin

I have a problem masking a phone input with jQuery and Masked Input Plugin.
There are 2 possible formats:
(XX)XXXX-XXXX
(XX)XXXXX-XXXX
Is there any way to mask it accepting both cases?
EDIT:
I tried:
$("#phone").mask("(99) 9999-9999");
$("#telf1").mask("(99) 9999*-9999");
$("#telf1").mask("(99) 9999?-9999");
But it doesn't works as I would like.
The closest one was (xx)xxxx-xxxxx.
I would like to get (xx)xxxx-xxxx when I type the 10th number, and (xx)xxxxx-xxxx when I type the 11th. Is it posible?
Try this - http://jsfiddle.net/dKRGE/3/
$("#phone").mask("(99) 9999?9-9999");
$("#phone").on("blur", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 3 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") - 1, 1 );
var lastfour = move + last;
var first = $(this).val().substr( 0, 9 );
$(this).val( first + '-' + lastfour );
}
});
Here is a jQuery phone number mask. No plugin required.
Format can be adjusted to your needs.
Updated JSFiddle.
HTML
<form id="example-form" name="my-form">
<input id="phone-number" name="phone-number" type="text" placeholder="(XXX) XXX-XXXX">
</form>
JavaScript
$('#phone-number', '#example-form')
.keydown(function (e) {
var key = e.which || e.charCode || e.keyCode || 0;
$phone = $(this);
// Don't let them remove the starting '('
if ($phone.val().length === 1 && (key === 8 || key === 46)) {
$phone.val('(');
return false;
}
// Reset if they highlight and type over first char.
else if ($phone.val().charAt(0) !== '(') {
$phone.val('('+$phone.val());
}
// Auto-format- do not expose the mask as the user begins to type
if (key !== 8 && key !== 9) {
if ($phone.val().length === 4) {
$phone.val($phone.val() + ')');
}
if ($phone.val().length === 5) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 9) {
$phone.val($phone.val() + '-');
}
}
// Allow numeric (and tab, backspace, delete) keys only
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.bind('focus click', function () {
$phone = $(this);
if ($phone.val().length === 0) {
$phone.val('(');
}
else {
var val = $phone.val();
$phone.val('').val(val); // Ensure cursor remains at the end
}
})
.blur(function () {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});
Actually the correct answer is on http://jsfiddle.net/HDakN/
Zoltan answer will allow user entry "(99) 9999" and then leave the field incomplete
$("#phone").mask("(99) 9999-9999?9");
$("#phone").on("blur", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 5 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") + 1, 1 );
var lastfour = last.substr(1,4);
var first = $(this).val().substr( 0, 9 );
$(this).val( first + move + '-' + lastfour );
}
});​
You need a jQuery plugin for the mask works as well.
-- HTML --
<input type="text" id="phone" placeholder="(99) 9999-9999">
<input type="text" id="telf1" placeholder="(99) 9999*-9999">
<input type="text" id="telf2" placeholder="(99) 9999?-9999">
-- JAVASCRIPT --
<script src="https://raw.githubusercontent.com/igorescobar/jQuery-Mask-Plugin/master/src/jquery.mask.js"></script>
<script>
$(document).ready(function($){
$("#phone").mask("(99) 9999-9999");
$("#telf1").mask("(99) 9999*-9999");
$("#telf2").mask("(99) 9999?-9999");
});
</script>
You can use the phone alias with Inputmask v3
$('#phone').inputmask({ alias: "phone", "clearIncomplete": true });
$(function() {
$('input[type="tel"]').inputmask({ alias: "phone", "clearIncomplete": true });
});
<label for="phone">Phone</label>
<input name="phone" type="tel">
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.numeric.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.date.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.phone.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/jquery.inputmask.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/phone-codes/phone.js"></script>
https://github.com/RobinHerbots/Inputmask#aliases
Using jQuery Mask Plugin there is two possible ways to implement it:
1- Following Anatel's recomendations:
https://gist.github.com/3724610/5003f97804ea1e62a3182e21c3b0d3ae3b657dd9
2- Or without following Anatel's recomendations:
https://gist.github.com/igorescobar/5327820
All examples above was coded using jQuery Mask Plugin and it can be downloaded at:
http://igorescobar.github.io/jQuery-Mask-Plugin/
var $phone = $("#input_id");
var maskOptions = {onKeyPress: function(phone) {
var masks = ['(00) 0000-0000', '(00) 00000-0000'];
mask = phone.match(/^\([0-9]{2}\) 9/g)
? masks[1]
: masks[0];
$phone.mask(mask, this);
}};
$phone.mask('(00) 0000-0000', maskOptions);
With jquery.mask.js
http://jsfiddle.net/brynner/f9kd0aes/
HTML
<input type="text" class="phone" maxlength="15" value="85999998888">
<input type="text" class="phone" maxlength="15" value="8533334444">
JS
// Function
function phoneMask(e){
var s=e.val();
var s=s.replace(/[_\W]+/g,'');
var n=s.length;
if(n<11){var m='(00) 0000-00000';}else{var m='(00) 00000-00000';}
$(e).mask(m);
}
// Type
$('body').on('keyup','.phone',function(){
phoneMask($(this));
});
// On load
$('.phone').keyup();
Only jQuery
http://jsfiddle.net/brynner/6vbrqe6z/
HTML
<p class="phone">85999998888</p>
<p class="phone">8599998888</p>
jQuery
$('.phone').text(function(i, text) {
var n = (text.length)-6;
if(n==4){var p=n;}else{var p=5;}
var regex = new RegExp('(\\d{2})(\\d{'+p+'})(\\d{4})');
var text = text.replace(regex, "($1) $2-$3");
return text;
});
The best way to do this is using the change event like this:
$("#phone")
.mask("(99) 9999?9-9999")
.on("change", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 3 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") - 1, 1 );
var lastfour = move + last;
var first = $(this).val().substr( 0, 9 ); // Change 9 to 8 if you prefer mask without space: (99)9999?9-9999
$(this).val( first + '-' + lastfour );
}
})
.change(); // Trigger the event change to adjust the mask when the value comes setted. Useful on edit forms.
The best way to do it on blur is:
function formatPhone(obj) {
if (obj.value != "")
{
var numbers = obj.value.replace(/\D/g, ''),
char = {0:'(',3:') ',6:' - '};
obj.value = '';
upto = numbers.length;
if(numbers.length < 10)
{
upto = numbers.length;
}
else
{
upto = 10;
}
for (var i = 0; i < upto; i++) {
obj.value += (char[i]||'') + numbers[i];
}
}
}
As alternative
function FormatPhone(tt,e){
//console.log(e.which);
var t = $(tt);
var v1 = t.val();
var k = e.which;
if(k!=8 && v1.length===18){
e.preventDefault();
}
var q = String.fromCharCode((96 <= k && k <= 105)? k-48 : k);
if (((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=8 && e.keyCode!=39) {
e.preventDefault();
}
else{
setTimeout(function(){
var v = t.val();
var l = v.length;
//console.log(l);
if(k!=8){
if(l<4){
t.val('+7 ');
}
else if(l===4){
if(isNaN(q)){
t.val('+7 (');
}
else{
t.val('+7 ('+q);
}
}
else if(l===7){
t.val(v+')');
}
else if(l===9){
t.val(v1+' '+q);
}
else if(l===13||l===16){
t.val(v1+'-'+q);
}
else if(l>18){
v=v.substr(0,18);
t.val(v);
}
}
else{
if(l<4){
t.val('+7 ');
}
}
},100);
}
}
I was developed simple and easy masks on input field to US phone format jquery-input-mask-phone-number
Simple Add jquery-input-mask-phone-number plugin in to your HTML file and call usPhoneFormat method.
$(document).ready(function () {
$('#yourphone').usPhoneFormat({
format: '(xxx) xxx-xxxx',
});
});
Working JSFiddle Link https://jsfiddle.net/1kbat1nb/
NPM Reference URL https://www.npmjs.com/package/jquery-input-mask-phone-number
GitHub Reference URL https://github.com/rajaramtt/jquery-input-mask-phone-number
If you don't want to show your mask as placeholder you should use jQuery Mask Plugin.
The cleanest way:
var options = {
onKeyPress: function(phone, e, field, options) {
var masks = ['(00) 0000-00000', '(00) 00000-0000'];
var mask = (phone.length>14) ? masks[1] : masks[0];
$('.phone-input').mask(mask, options);
}
};
$('.phone-input').mask('(00) 0000-00000', options);
Yes use this
$("#phone").inputmask({"mask": "(99) 9999 - 9999"});
Link here
$('.phone').focus(function(e) {
// add mask
$('.phone')
.mask("(99) 99999999?9")
.focusin(function(event)
{
$(this).unmask();
$(this).mask("(99) 99999999?9");
})
.focusout(function(event)
{
var phone, element;
element = $(this);
phone = element.val().replace(/\D/g, '');
element.unmask();
if (phone.length > 10) {
element.mask("(99) 99999-999?9");
} else {
element.mask("(99) 9999-9999?9");
}
}
);
});

Categories

Resources