Contact form Phone Number format Javascript - 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
}

Related

Format an input field for US number

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' />

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;
}

Synchronous input update with selected digit in HTML/JavaScript

I'm trying to implement a customised input that can use left or right arrow key to select the digit and use up/down arrow key to increment/decrement the digit. Here's the code in jsfiddle: http://jsfiddle.net/uk5t3z4d/48/. However, I have two problems:
I cannot add digit using the number pad, the input always stays at X.XX
When I use another function I wrote (parseLocalFloat which is commented out), the output stops displaying anything, and I cannot use the left and right key to select the digit etc.
How can I overcome these two issues? Please shed a light on me, thanks!
HTML
<div class="display" id="out"></div>
<div class="form-group">
<label for="comment">value:</label>
<input class="form-control" type="text" value="0.00" id="in"></input>
</div>
JavaScript
function createSelection(field, start, end) {
if( field.createTextRange ) {
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart('character', start);
selRange.moveEnd('character', end);
selRange.select();
} else if( field.setSelectionRange ) {
field.setSelectionRange(start, end);
} else if( field.selectionStart ) {
field.selectionStart = start;
field.selectionEnd = end;
}
}
function getLocalDecimalSeparator() {
var n = 1.1;
return n.toLocaleString().substring(1,2);
}
function parseLocalFloat(num) {
return +(num.replace(getLocalDecimalSeparator(), '.'));
}
var inputBox = document.getElementById('in');
//var inputBox = parseLocalFloat(document.getElementByID('in').value);
inputBox.onkeyup = function(){
document.getElementById('out').innerHTML = inputBox.value;
}
$('#in').on("keydown", function(e){
var gotCode = false;
var curPos = this.selectionStart;
var endPos = this.selectionEnd;
if(curPos !== endPos) {
createSelection(this, curPos, curPos+1);
}
// get the position
if(e.keyCode == 37){
curPos--;
gotCode=true;
}
if(e.keyCode == 39){
curPos++;
gotCode=true;
}
var before = $(this).val().substring(0,curPos);
var after = $(this).val().substring(curPos+1);
var cur = Number($(this).val().substring(curPos, curPos+1));
// avoid adding extra stuff
if(curPos < $(this).val().length) {
if(e.keyCode == 38) {
cur++;
if(cur > 9) cur = 0;
$(this).val(before + '' + cur + '' + after);
gotCode=true;
}
if(e.keyCode == 40) {
cur--;
if(cur < 0) cur = 9;
$(this).val(before + '' + cur + '' + after);
gotCode=true;
}
}
if(!gotCode) {
e.preventDefault();
return false;
}
var field = this;
window.setTimeout(function(){
createSelection(field, curPos, curPos+1);
}, 10);
});
as for the "get number keys to work":
as stated you need to add the keys you want to support:
if(e.keyCode >= 48 && e.keyCode <= 57) {
var num = e.keyCode - 48; // 0=48; 9=59
$(this).val(before + '' + num + '' + after);
gotCode = true;
e.preventDefault(); // otherwise a new number is added as well
}
(this needs to come before the if (!gotCode) ... )
as for the customFloat: the the response from Moishe
For #1:
if(!gotCode) {
e.preventDefault();
return false;
}
ensures that if gotCode is false the default event (which in this case is the default keydown event) will not occur.
gotCode only seems to be true if keyCode is equal to 37, 38, 39, or 40 (the arrow keys). You are essentially preventing the other keys (like number keys) from having any effect on the textBox.
You probably would like to enable the number keys (when shift or caps aren't on) and number pad keys.
Additionally, you may want to check that the cur is a number (and not .) before attempting to increment or decrement its value.
You could do:
var isNumberKey = (
( e.keyCode >= 48 //is more than or equal to 0 key
&& e.keyCode <= 57 //is less than or equal to 9 key
&& !e.shiftKey) //shift key or cap key not on
|| ( e.keyCode >= 96 //more than or equal to 0 key in number pad
&& e.keyCode <= 105)); //less than or equal to 9 key in number pad
if(!gotCode && !isNumberKey) { //not arrow key or number key
console.log(e);
e.preventDefault();
return false;
}
For #2:
var inputBox = parseLocalFloat(document.getElementByID('in').value);
is setting inputBox to whatever parseLocalFloat returns which happens to be a number.
This is problematic because you then attempt to attach a keyUp event to that number instead of the inputBox:
inputBox.onkeyup = function(){
document.getElementById('out').innerHTML = inputBox.value;
}
You may want to instead call parseLocalFloat on the number and set the out textBox's value to that:
var inputBox = document.getElementById('in');
inputBox.onkeyup = function(){
document.getElementById('out').innerHTML = parseLocalFloat(inputBox.value);
}
function createSelection(field, start, end) {
if( field.createTextRange ) {
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart('character', start);
selRange.moveEnd('character', end);
selRange.select();
} else if( field.setSelectionRange ) {
field.setSelectionRange(start, end);
} else if( field.selectionStart ) {
field.selectionStart = start;
field.selectionEnd = end;
}
}
function getLocalDecimalSeparator() {
var n = 1.1;
return n.toLocaleString().substring(1,2);
}
function parseLocalFloat(num) {
return +(num.replace(getLocalDecimalSeparator(), '.'));
}
var inputBox = document.getElementById('in');
// var inputBox = parseLocalFloat(document.getElementByID('in').value);
inputBox.onkeyup = function(){
document.getElementById('out').innerHTML = parseLocalFloat(inputBox.value);
}
$('#in').on("keydown", function(e){
var gotCode = false;
var curPos = this.selectionStart;
var endPos = this.selectionEnd;
if(curPos !== endPos) {
createSelection(this, curPos, curPos+1);
}
// get the position
if(e.keyCode == 37){
curPos--;
gotCode=true;
}
if(e.keyCode == 39){
curPos++;
gotCode=true;
}
var $thisVal = $(this).val();
var before = $thisVal.substring(0,curPos);
var after = $thisVal.substring(curPos+1);
var cur = Number($thisVal.substring(curPos, curPos+1));
// avoid adding extra stuff
if(curPos < $thisVal.length && !isNaN(cur)) {
if(e.keyCode == 38) {
cur++;
if(cur > 9) cur = 0;
$(this).val(before + '' + cur + '' + after);
gotCode=true;
}
if(e.keyCode == 40) {
cur--;
if(cur < 0) cur = 9;
$(this).val(before + '' + cur + '' + after);
gotCode=true;
}
}
var isNumberKey = ((e.keyCode >= 48 && e.keyCode <= 57 && [16, 20].indexOf(e.keyCode) == -1 && !e.shiftKey) || (e.keyCode >= 96 && e.keyCode <= 105));
if(!gotCode && !isNumberKey) {
console.log(e);
e.preventDefault();
return false;
}
var field = this;
window.setTimeout(function(){
createSelection(field, curPos, curPos+1);
}, 10);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="display" id="out"></div>
<div class="form-group">
<label for="comment">value:</label>
<input class="form-control" type="text" value="0.00" id="in"></input>
</div>

keypress,keyup and change events on inputs with same class name

i have a table where the first row are all text inputs sharing the same class name. i would like to set a validation so that user only enters float numbers. Does anyone know what i may be missing on the following code? $('input.' + classname) or $('.classname) doesn't fire any event when calling floatTextField() function
HTML code:
<td><div class="input-group"><input type="text" class="form-control myclass" value="2.8"></div> </td>
JavaScript code:
floatTextField('myclass');
function floatTextField(classname) {
$('input.' + classname).keypress(function (event) {
var charCode = (event.which) ? event.which : event.keyCode;
if (event.which == 0)//common keys
return true;
var value = $(this).val();
if (charCode == 45 && value.indexOf('-') != -1) {
return false;
}
else if (charCode == 46 && value.indexOf('.') != -1)
return false;
else if (charCode != 46 && charCode != 45 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
});
$('input.' + classname).keyup(function (event) {
var value = $(this).val();
if (value <= 0 && value.indexOf('.') == -1 && value.indexOf('-') == -1) {
$(this).val('');
}
if (value.indexOf('-') > 0) {
value = value.replace('-', '');
$(this).val(value);
}
});
$('input.' + classname).change(function (event) {
var value = $(this).val();
if (value.indexOf('.') == 0) {
value = '0' + value;
$(this).val(value);
}
});
}
You must use the $(document).ready() method like this:
function floatTextField(classname) {
$('input.' + classname).keypress(function (event) {
var charCode = (event.which) ? event.which : event.keyCode;
if (event.which == 0)//common keys
return true;
var value = $(this).val();
if (charCode == 45 && value.indexOf('-') != -1) {
return false;
}
else if (charCode == 46 && value.indexOf('.') != -1)
return false;
else if (charCode != 46 && charCode != 45 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
});
$('input.' + classname).keyup(function (event) {
var value = $(this).val();
if (value <= 0 && value.indexOf('.') == -1 && value.indexOf('-') == -1) {
$(this).val('');
}
if (value.indexOf('-') > 0) {
value = value.replace('-', '');
$(this).val(value);
}
});
$('input.' + classname).change(function (event) {
var value = $(this).val();
if (value.indexOf('.') == 0) {
value = '0' + value;
$(this).val(value);
}
});
}
$(document).ready(function(){
floatTextField('myclass');
});

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