Format an input field for US number - javascript

I am having a small issue with my code and I am not able to crack it, the format I want is
+1 (888) 123-4567 . However I have achieved this (544)-646-4646 format. But I am unable to figure how can i get +1 already written and when someone types number the remaining should be formatted as the above example.
so in simple words I need +1 to be already typed and rest when typed by user would give the same format as the code.
Here is the code
$(document).ready(function(){
/***phone number format***/
$(".phone-format").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
var curchr = this.value.length;
var curval = $(this).val();
if (curchr == 3 && curval.indexOf("(") <= -1) {
$(this).val("(" + curval + ")" + "-");
} else if (curchr == 4 && curval.indexOf("(") > -1) {
$(this).val(curval + ")-");
} else if (curchr == 5 && curval.indexOf(")") > -1) {
$(this).val(curval + "-");
} else if (curchr == 9) {
$(this).val(curval + "-");
$(this).attr('maxlength', '16');
}
});
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<input class="phone-format" value="" type="text" placeholder="Phone Number">
</body>
</html>

You can try this:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<input class="phone-format" value="+1 " type="text" placeholder="Phone Number">
</body>
</html>
And in js file:
$(document).ready(function(){
/***phone number format***/
$(".phone-format").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
var curchr = this.value.length;
var curval = $(this).val();
if (curchr == 6 && curval.indexOf("(") <= -1) {
$(this).val(curval.substring(0, 2) + " (" + curval.substring(3) + ")" + "-");
} else if (curchr == 7 && curval.indexOf("(") > -1) {
$(this).val(curval + ")-");
} else if (curchr == 8 && curval.indexOf(")") > -1) {
$(this).val(curval + "-");
} else if (curchr == 12){
$(this).val(curval + "-");
$(this).attr('maxlength', '16');
}
});
});

Try the jquery input mask plugin
You just need to specify the mask/format you want your input to be in and it does the job.
$(window).load(function()
{
$('#phone').inputmask({"mask": "+1(999) 999-9999"});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.1.62/jquery.inputmask.bundle.js"></script>
<input type='text' id='phone' />

Related

Can't enter numbers using numbers pad

I have a function that formats user input into phone format.
It works fine except it's not allowing numbers from numbers pad at the right, Only the numbers at the top of the alphabetic characters.
I want to keep the same format, But allow entering numbers from numbers pad.
Here is a fiddle:
https://jsfiddle.net/s1wyrmk6
Here is the code:
HTML:
<input type="text" id="phone">
JS/jQuery:
(function ($) {
$.fn.usPhoneFormat = function (options) {
var params = $.extend({
format: 'xxx-xxx-xxxx',
international: false,
}, options);
if (params.format === 'xxx-xxx-xxxx') {
$(this).bind('paste', function (e) {
e.preventDefault();
var inputValue = e.originalEvent.clipboardData.getData('Text');
if (!$.isNumeric(inputValue)) {
return false;
} else {
inputValue = String(inputValue.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3"));
$(this).val(inputValue);
$(this).val('');
inputValue = inputValue.substring(0, 12);
$(this).val(inputValue);
}
});
$(this).on('keydown touchend', function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
var curchr = this.value.length;
var curval = $(this).val();
if (curchr == 3 && e.which != 8 && e.which != 0) {
$(this).val(curval + "-");
} else if (curchr == 7 && e.which != 8 && e.which != 0) {
$(this).val(curval + "-");
}
$(this).attr('maxlength', '12');
});
} else if (params.format === '(xxx) xxx-xxxx') {
$(this).on('keydown touchend', function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
var curchr = this.value.length;
var curval = $(this).val();
if (curchr == 3 && e.which != 8 && e.which != 0) {
$(this).val('(' + curval + ')' + " ");
} else if (curchr == 9 && e.which != 8 && e.which != 0) {
$(this).val(curval + "-");
}
$(this).attr('maxlength', '14');
});
$(this).bind('paste', function (e) {
e.preventDefault();
var inputValue = e.originalEvent.clipboardData.getData('Text');
if (!$.isNumeric(inputValue)) {
return false;
} else {
inputValue = String(inputValue.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3"));
$(this).val(inputValue);
$(this).val('');
inputValue = inputValue.substring(0, 14);
$(this).val(inputValue);
}
});
}
}
}(jQuery));
Change the following
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { return false; }
The additional range 96 to 105 is greater than 57 currently, which causes this statement to catch the numpad.
To allow the numpad:
if (e.which != 8 && e.which != 0 && (e.which < 48 || (e.which > 57 && !(e.which>=96 && e.which<=105 )))) {
return false;
}

Contact form Phone Number format Javascript

This piece of code lets me write a phone number to my contact form as (XXX) XXX-XXXX format. (working example is at https://www.fxmerkezi.com/ucretsiz-danismanlik/)
But I need it to be done like 0XXXXXXXXXX first character must be 0 and no letters or any other characters shouldt be allowed.
This is the code in my head tags;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/jquery-input-mask-phone-number#1.0.0/dist/jquery-input-mask-phone-number.js"></script>
<script>
$(document).ready(function () {
$('#yourphone').usPhoneFormat({
format: '(xxx) xxx-xxxx',
});
$('#yourphone2').usPhoneFormat();
});
</script>
And this is the file jquery-input-mask-phone-number.js:
(function ($) {
$.fn.usPhoneFormat = function (options) {
var params = $.extend({
format: 'xxx-xxx-xxxx',
international: false,
}, options);
if (params.format === 'xxx-xxx-xxxx') {
$(this).bind('paste', function (e) {
e.preventDefault();
var inputValue = e.originalEvent.clipboardData.getData('Text');
if (!$.isNumeric(inputValue)) {
return false;
} else {
inputValue = String(inputValue.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3"));
$(this).val(inputValue);
$(this).val('');
inputValue = inputValue.substring(0, 12);
$(this).val(inputValue);
}
});
$(this).on('keypress', function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
var curchr = this.value.length;
var curval = $(this).val();
if (curchr == 3) {
$(this).val(curval + "-");
} else if (curchr == 7) {
$(this).val(curval + "-");
}
$(this).attr('maxlength', '12');
});
} else if (params.format === '(xxx) xxx-xxxx') {
$(this).on('keypress', function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
var curchr = this.value.length;
var curval = $(this).val();
if (curchr == 3) {
$(this).val('(' + curval + ')' + " ");
} else if (curchr == 9) {
$(this).val(curval + "-");
}
$(this).attr('maxlength', '14');
});
$(this).bind('paste', function (e) {
e.preventDefault();
var inputValue = e.originalEvent.clipboardData.getData('Text');
if (!$.isNumeric(inputValue)) {
return false;
} else {
inputValue = String(inputValue.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3"));
$(this).val(inputValue);
$(this).val('');
inputValue = inputValue.substring(0, 14);
$(this).val(inputValue);
}
});
}
}
}(jQuery));
just simply define your textbox as below which will allow only 11 digits with starting 0.
$( document ).ready(function() {
$( "#number" ).keypress(function(e) {
if(this.value.length == 0 && e.which != 48){
return false
}
if(e.which < 48 || e.which > 57 || this.value.length > 10){
return false
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="">
<input type="text" id="number" name="country_code" pattern="[0]{1}[0-9]{10}">
<input type="submit" value="ok">
</form>
You can write regex to match the format you want,
let regex = /[0]\d+/gi;
let match = regex.exec(e);
if(match && match.length == 11){
return true; // match found with 11 digits number starting with 0
}
else{
alert('invalid number'); // no match found
}

How to replace text when selected in javascript

I have the below phone number validation which automatically picks up brackets based on the condition.
I have an issue here, after giving the 10 digit phone number when we try to select the whole number and start typing on top of it, length of the value remains same (14) and brackets are not picking up and condition goes wrong.
Length should be cleared in this case.
Where am I missing?
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.validatePhoneNumber = function(e){
var key = e.charCode || e.keyCode || 0;
// var regex = /^[0-9.\-\(\)]*$/;
var text = $('#phoneNumber');
console.log(text.val());
if ((e.which < 48 || e.which > 57)) {
e.preventDefault();
} else if (key !== 8 && key !== 9) {
if ((text.val().length === 0) && (!e.ctrlKey)) {
text.val(text.val() + '(');
}
if (text.val().length === 4) {
text.val(text.val() + ') ');
}
if (text.val().length === 9) {
text.val(text.val() + '-');
}
}
return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="text" class="input-sm form-control" id="phoneNumber"
ng-model="search.phonenumber" placeholder="Phone Number"
ng-keypress="validatePhoneNumber($event)"
ng-paste="$event.preventDefault();"
ng-init="paste=false" maxlength="14">
</div>
I have used keyup here hope this will help you
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="text" class="input-sm form-control" id="phoneNumber" ng-model="search.phonenumber" placeholder="Phone Number" ng-keyup="validatePhoneNumber($event)" ng-paste="$event.preventDefault();" ng-init="paste=false" maxlength="14">
</div>
</body>
</html>
JS
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.validatePhoneNumber = function(e) {
var key = e.charCode || e.keyCode || 0;
// var regex = /^[0-9.\-\(\)]*$/;
var text = $('#phoneNumber');
console.log(text.val());
if ((e.which < 48 || e.which > 57)) {
e.preventDefault();
}
if(text.val().length === 1) {
if(!isNaN(text.val())) {
text.val('(' + text.val());
}
}
if ((text.val().length === 0) && (!e.ctrlKey)) {
text.val(text.val() + '(');
}
if (text.val().length === 4) {
text.val(text.val() + ') ');
}
if (text.val().length === 9) {
text.val(text.val() + '-');
}
return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
}
});
You may want to take a look at angular-input-masks package. It appears to implement the required logic by ui-us-phone-number-mask directive:
var app = angular.module('myApp', ['ui.utils.masks']);
app.controller('myCtrl', function() {});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-input-masks/4.2.1/angular-input-masks-standalone.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<input ui-us-phone-number-mask type="text" class="input-sm form-control" id="phoneNumber" ng-model="search.phonenumber" phone-number placeholder="Phone Number" ng-paste="$event.preventDefault();" ng-init="paste=false" maxlength="14">
</div>

How to restrict zero at second position

In the below code the text box is restricting zero at starting position. But I want to allow only one zero at first position but not more than one. here is the example
Eg:- 0.1012400==> correct
000.4545000==>not correct
0154==> correct
00154 ==> not correct
$('input#abc').keypress(function(e){
if (this.selectionStart == 0 && (e.which == 48 || e.which == 46 )){
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="abc">
You can simply test if there is 2 consecutive zero at the start and if yes you remove one:
$('input#abc').on('keypress keydown keyup',function(e){
var v = $(this).val();
if(v.length >=2 && v[0]=='0' && v[1]=='0') {
$(this).val(v.substring(1));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="abc">
UPDATE
Here is a code if you want to consider the minus sign at the start:
$('input#abc').on('keypress keydown keyup', function(e) {
var v = $(this).val();
if (v.length >= 2 && v[0] == '0' && v[1] == '0') {
$(this).val(v.substring(1));
} else if (v.length >= 3 && v[0] == '-' && v[1] == '0' && v[2] == '0') {
$(this).val('-' + v.substring(2));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="abc">
You could check the final string like
$('input#abc').on('change', function () {
console.log(this.value.indexOf('00') === 0);
});

How to make this validation work on cloned inputs

I have this id validation field, i just need to know how i can make the validation and the keydown and keyup functions work on cloned inputs. also inserted data is carrying over to the duplicate fields.
js fiddle- http://www.jsfiddle.net/dawidvdh/xRh9v/
Heres the js:
$(document).ready(function() {
idAmount = [0,1,2,3,4,5,6,7,8,9,10,12,13];
var idinc =1;
var id_val;
jQuery(idAmount).each(function() {
var index = "id"+idinc++;
var id_input = "<input class='id' id="+'"'+index+'"'+" "+" maxlength='1' />";
id_val = $(this).attr('value');
jQuery(id_input).appendTo('#id');
});
$("#clone").click(function () {
var clonedObj=$('#id').clone().insertAfter("#id");
clonedObj.find('.id').each(function(){
this.id='id' + idinc++;
});
});
function Validate() {
jQuery('#error p').remove();
var id_val = '';
$('.id').each(function(){ id_val+=($(this).val());});
var idNumber = id_val;
console.log(id_val);
var correct = true;
if (idNumber.length != 13 || !isNumber(idNumber)) {
correct = false;
}
var tempDate = new Date(idNumber.substring(0, 2), idNumber.substring(2, 4) - 1, idNumber.substring(4, 6));
console.log(tempDate);
var id_date = tempDate.getDate();
var id_month = tempDate.getMonth();
var id_year = tempDate.getFullYear();
var currentYear = (new Date).getFullYear();
var age = currentYear - id_year;
var fullDate = id_date + "-" + (id_month + 1) + "-" + id_year;
if (!((tempDate.getYear() == idNumber.substring(0, 2)) && (id_month == idNumber.substring(2, 4) - 1) && (id_date == idNumber.substring(4, 6)))) {
correct = false;
}
// get the gender
var genderCode = idNumber.substring(6, 10);
var gender = parseInt(genderCode) < 5000 ? "Female" : "Male";
// get country ID for citzenship
var citzenship = parseInt(idNumber.substring(10, 11)) == 0 ? "Yes" : "No";
// apply Luhn formula for check-digits
var tempTotal = 0;
var checkSum = 0;
var multiplier = 1;
for (var i = 0; i < 13; ++i) {
tempTotal = parseInt(idNumber.charAt(i)) * multiplier;
if (tempTotal > 9) {
tempTotal = parseInt(tempTotal.toString().charAt(0)) + parseInt(tempTotal.toString().charAt(1));
}
checkSum = checkSum + tempTotal;
multiplier = (multiplier % 2 == 0) ? 1 : 2;
}
if ((checkSum % 10) != 0) {
correct = false;
};
// if no error found, hide the error message
if (correct) {
jQuery('.id').css("border","1px solid #9A8B7D");
// clear the result div
jQuery('#result').empty();
// and put together a result message
jQuery('#result').append('<p>South African ID Number: ' + idNumber + '</p><p>Birth Date: ' + fullDate + '</p><p>Gender: ' + gender + '</p><p>SA Citizen: ' + citzenship + '</p><p>AGE: ' + age + '</p>');
jQuery('#status').html("correct");
}
// otherwise, show the error
else {
jQuery('.id').css("border","1px solid #FF0000");
jQuery('#status').html("incorrect")
}
return false;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
$('input.id').keydown(function(e){
if(e.keyCode == 8){
$(this).val('');
$(this).prev().val('');
$(this).prev().focus();
Validate()
}
});
$('input.id').on('keyup', function(){
if (this.value.match(/\d+/)) {
var $this = $(this);
if ($this.next('input').length) {
$this.next().focus();
} else {
Validate()
}
}
});
$(".id").keydown(function(event) {
// Allow: backspace, delete, tab, escape, and enter
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
});
});
HTML:
<div id="id">
<span id="label">ID NUMBER:</span>
<span id="status"></span>
</div>
<button id="clone">clone</button>
<div id="result"> </div>
CSS:
#error {
color: red;
border: 1px solid red;
padding: 5px;
display: none;
}
#result {
padding: 20px;
}
.id {
width:16px;
height:16px;
border:1px solid #9A8B7D;
margin:0;
float:left;
text-align:center;
font-family:'itc_avant_garde_gothic_bookOb',Helvetica,sans-serif;
font-size:11pt;
padding:2px;
}
#label {
float:left;
font-family:'itc_avant_garde_gothic_bookOb',Helvetica,sans-serif;
line-height:18px;
font-size:11pt;
margin-right:10px;
}
The only time that I see you call Validate is here :
$('input.id').on('keyup', function(){
//code
});
and here
$('input.id').keydown(function(e){
//code
});
Which means that the issue is the event handler is not delegated to a static element
$(document).on('keyup', 'input.id', function(){
//code
});
$(document).on('keydown', 'input.id', function(){
//code
});
Binding it to the document will ensure that any dynamically created elements will have the same event delegated to them as any static elements of the same selector.
Forgot the last part.
clonedObj.find('.id').each(function(){
this.id='id' + idinc++;
this.value = ''; //simply add this to remove the value
});
Although, because you're using jQuery, you should try to stick to using jQuery.
clonedObj.find('.id').each(function(){
$(this).prop('id', 'id'+ idinc++).val(''); // chain the commands
});

Categories

Resources