Custom mask for phone numbers - javascript

I am using the jsmask plugin to mask telephone numbers.
The requirements are
It can have optional + at the start
It can have spaces in between
I tried this
$('#Telephone').mask('+0000000 000 000 0000', { reverse: true });
but it aint accepting optional plus.
Is there an inbuilt format or can we have a custom format for it
Please advise.

That's impossible.
You can add optional parameters only in end of the input.
They have an open pull request in Github.
You can check it here.

Following code is working, you can try it.I have created solution in JSfidller for you. check it if you want.
HTML:
<form id="example-form" name="my-form">
<label>Phone number:</label><br />
<input id="phone-number" name="phone-number" type="text" maxlength="21" placeholder="+XXXXXXX XXX XXX XXXX" /><br /><br />
<input type="button" value="Submit" />
</form>
Script:
$('#phone-number', '#example-form')
.keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);
// Adding blankspace in 9th, 13th and 17th position.
//Change it according to your need
if (key !== 8 && key !== 9) {
if ($phone.val().length === 8) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 12) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 16) {
$phone.val($phone.val() + ' ');
}
}
// Allow numeric number and tab, backspace, delete keys only.
//Change it according to your need
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('+'); // as your phone number start with '+'
}
else {
var val = $phone.val();
$phone.val('').val(val); // Ensure cursor remains at the end
}
})
.blur(function () {
$phone = $(this);
if ($phone.val() === '+') {
$phone.val(''); // if somebody type '+' it will be vanish
}
});

Related

Applying changes to text on pasting into input instead of key down entery

I am trying to append - between phone numbers in user input to be like xxx-xxx-xxxx instead of xxxxxxxxxx .
This is working fine when using Keys to enter value but what about Pasting the number or Chrome Auto-fill function? For example if you copy and paste 2222222222 to the input the - will not added between.
How can I fix this?
$(function () {
$('#txtnumber').keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$text = $(this);
if (key !== 8 && key !== 9) {
if ($text.val().length === 3) {
$text.val($text.val() + '-');
}
if ($text.val().length === 7) {
$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/3.3.1/jquery.min.js"></script>
<input id="txtnumber" type="text" maxlength="12" placeholder="xxx-xxx-xxxx" /><br /><br />
you need to capture the Ctrl key + V, and then insert your -'s
var ctrlDown = false,
ctrlKey = 17,
cmdKey = 91,
vKey = 86,
cKey = 67;
$(document).keydown(function(e) {
if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = true;
}).keyup(function(e) {
if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = false;
});
/// your code +
$(function () {
$('#txtnumber').keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
if (ctrlDown && (e.keyCode == vKey)){
//insert the -'s on respective possition
}
else{
$text = $(this);
if (key !== 8 && key !== 9) {
if ($text.val().length === 3) {
$text.val($text.val() + '-');
}
if ($text.val().length === 7) {
$text.val($text.val() + '-');
}
}
}
credits to> https://stackoverflow.com/a/2904944/335905
Original answer (look at the update) [interesting]
Add a change event listener to the input, because keydown is not emmitted when pasting
Something like this should work
$('#txtnumber').change(function(e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{3})(\d{3})(\d{4})/);
e.target.value = x[1] + '-' + x[2] + '-' + x[3];
});
 Update
Working always on vuejs. Change is the thing. Apparently not for purejs and in google chrome (i will test for other browser later)
For some reason, the change event only fires when the input field loses focus.
Binding to other options ('change keypress paste focus textInput input') will fire the event several times, which is bad.
The below code works even when content is pasted into the text field, and only fires once as expected.
input event come to the rescue (or simple it's our event) (change however is confusing).
$('#txtnumber').bind('input', function(e) {
console.log('This actually fires');
console.log(e.target.value);
});
And a pure js
document.getElementById('txtnumber').addEventListener('input', function(e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{3})(\d{3})(\d{4})/);
e.target.value = x[1] + '-' + x[2] + '-' + x[3];
});
Final Example
$('#txtnumber').bind('input', function(e) {
if (e.target.value.length === 10) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{3})(\d{3})(\d{4})/);
e.target.value = x[1] + '-' + x[2] + '-' + x[3];
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="txtnumber" type="text" maxlength="12" placeholder="xxx-xxx-xxxx" /><br /><br />

Allow 2 digit number after the decimal

Hi i am trying to restrict user to input 2 digit number after the decimal.The below functionality is working but i am not able to modify the last two digit.suppose I have entered number 3456.78 and i want to modify 3456.68 it is not allowing.
$('.PMT_AMT').keypress(function(event) {
var $this = $(this);
if ((event.which != 46 || $this.val().indexOf('.') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8))) {
event.preventDefault();
}
var text = $(this).val();
if ((event.which == 46) && (text.indexOf('.') == -1)) {
setTimeout(function() {
if ($this.val().substring($this.val().indexOf('.')).length > 3) {
$this.val($this.val().substring(0, $this.val().indexOf('.') + 3));
}
}, 1);
}
if ((text.indexOf('.') != -1) &&
(text.substring(text.indexOf('.')).length > 2) &&
(event.which != 0 && event.which != 8) &&
($(this)[0].selectionStart >= text.length - 2)) {
event.preventDefault();
}
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">
Here's one possibility that uses a regular expression. Save the old input value on keypress, and if the new value on keyup does not validate, reset to that old value.
You need to validate on keypress as well, because otherwise, if the user types very fast, an invalid value can be saved:
const re = /^\d+(\.\d{0,2})?$/;
let oldVal;
$('.PMT_AMT').keypress(function(event) {
const { value } = this;
if (re.test(value)) oldVal = value;
});
$('.PMT_AMT').keyup(function(event) {
const newVal = this.value;
if (!re.test(newVal)) this.value = oldVal;
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">
This solution creates a prediction and tests the regular expression against that instead.
$('.PMT_AMT').keypress(function(event) {
if(!/^\d*(\.\d{0,2})?$/.test(
this.value.slice(0, this.selectionStart)
+ String.fromCharCode(event.which)
+ this.value.slice(this.selectionEnd)
)) event.preventDefault();
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">
Why use jQuery and not just browser functionality?
<input type="number" step="0.01">
On submit the browser will check if the submitted value of the input field has maximum two decimals.

How to allow only numbers as input in Javascript , why doesn't my code work?

I want write a function to prevent any input other than numbers 0-9 and the return key so the user can make corrections. I know that this type of question have been asked several times but why doesn't my code work. Does it has to do with the shift key? Why am I getting "event is not defined"?
In the snippet I can prevent letters but special characters, like #, keep being inserted. Why am I getting a reference error?
// I have two functions
function formatarCPF(event, controle) {
//this line check the returned value from the functions defined below
var eNumero = permitirApenasNumeros(event.keyCode);
if (!eNumero)
event.preventDefault();
if (event.keyCode != 8) {
var valor = controle.value;
if (valor.length == 3) {
controle.value = (controle.value + ".");
}
if (valor.length == 7) {
controle.value = (controle.value + ".");
}
if (valor.length == 11) {
controle.value = (controle.value + "-");
}
}
}
if(event.keyCode != 8) {
var valor = controle.value;
if (valor.length == 0) {
controle.value = "(";
}
if(valor.length == 2) {
controle.value = (controle.value + String.fromCharCode(event.which) + ")");
event.preventDefault();
}
if (valor.length == 9) {
controle.value = (controle.value + "-");
}
}
function permitirApenasNumeros(code) {
//checks to see if the user typed a number
var regex = /[0-9]/;
if(regex.test(String.fromCharCode(code)) || code == 8) {
return true;
} else {
return false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div>
<label for="tbCPF">CPF:</label>
<input onkeydown="formatarCPF(event, this)" maxlength="14" placeholder="___.___.___-__" />
</div>
Try HTML5
<input type="number" />
Or regex
<input type="text" pattern="^[0-9]*$" />
Your code formatting has many issues that make it nearly impossible to read, but it seems to me that the problem is your second if(event.keyCode != 8) { block that is outside the formatarCPF event listener. Since it is outside, the event variable isn't defined.
If you format your code properly this would be super trivial to catch. You can use tools like jsbeautifier to do it for you if you prefer.
To allow only numbers inside an HTML Input Element just set its type to number
<input min='0' type="number">
Why not simply scrap all that JavaScript and use:
<input type="text" onkeypress="return event.charCode >= 48 && event.charCode <= 57">
This should work
HTML
<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" />
JAVASCRIPT
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}

Form Validation Jquery object

I am trying to format the phone number field based on the country .The logic works fine when the user fill in the details but does not work when the country is changed and filled in again.
Ex:
Filled in the form for Germany and then without reloading the page if try change county to US and fill in phone "+" is being added even though format for it is different.
$(document).ready(function($){
$('#country').on('change', function() {
if ( this.value == 'US' || this.value == 'CA')
{
$('#C_BusPhone')
.keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);
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() + '-');
}
}
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);
}
})
.blur(function () {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});
}
else
{
$('#C_BusPhone')
.keydown(function (e) {
if ($(this).val().indexOf("+") === -1) {
$(this).val("+" + $this.val());
}
})
}
});
});
Not sure if this was the cause for your error, but this line needs to get corrected from
$(this).val("+" + $this.val());
to this
$(this).val("+" + $(this).val());
It was a fast catch, just use your browser javascript console for debugging.
See the updated fiddle here. You might want to add the starting parenthesis to your international prefix as well.

How the DEL Key with Mozilla Firefox

I need the help for my problem in my asp.net MVC3 application I have a textbox which is validating for currency format ($228.00) but in this text box it doesn't work for the DEL key because . and delete key have same ASCII key which 46. I also set a validation in this textbox for . is only one time will be accept in the text box so if "." entered one time then delete will not work.
Here is my validate Javascript:
function validateForCharacter(val, id, e) {
window.event.keyCode : -1;
var key = e.keyCode || e.charCode || e.which;
var currentChar = String.fromCharCode(key);
if (val.indexOf(currentChar) != -1 && currentChar == ".")
{
return false;
}
if (key >= 48 && key <= 57 || key == 46 || e.keyCode === 8 || e.keyCode === 9 || e.keyCode === 37 || e.keyCode === 35 || e.keyCode === 39)
{
$(this).val("");
return true;
}
return false;
}
This is my View (Html) code for textbox:
<input type="text" id="t1" onkeypress="return validateForCharacter(value, id, event)/>
Jquery does it right... but in case you need specifically detect delete key on Firefox or IE9 you can use event.key property.
I.E:
if (event.key == "Delete")
Live Demo:
$(document).ready(function() {
$("#nondeletable").on("keydown", function(event) {
$("#result").html(event.type + ": " + event.which);
if (event.key == "Delete")
$("#result").append(" <b>Delete!</b>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="nondeletable" />
<div id="result"></div>

Categories

Resources