phone number validation with added input - javascript

I recently filled out a form and when I got to the phone number textBox I noticed some really cool things going on. As I entered my number, general phone symbols were getting added automatically. Example:
I start entering my area code '555'
and my input was changed to 1 (555)
to test what just happened I backspaced on the ) and it quickly added it back in.
So my question is, how do I get this input to happen?

I use a javascript library called automask - you dont see the mask but it wont let you type anything outside the mask
for instance if your mask is ###-###-#### then any other characters are ignored (ie not 0-9) and the dashes are put in automatically.
I can post the library if you would like to take a look at
example of implementation
<input type=text name=ssn onkeypress="return autoMask(this,event, '###-##-####');">
// email kireol at yahoo.com
// autoMask - an adaption of anyMask
//
// this will force #'s, not allowing alphas where the #'s are, and auto add -'s
function autoMask(field, event, sMask) {
//var sMask = "**?##?####";
var KeyTyped = String.fromCharCode(getKeyCode(event));
var targ = getTarget(event);
keyCount = targ.value.length;
if (getKeyCode(event) < 32)
{
return true;
}
if(keyCount == sMask.length && getKeyCode(event) > 32)
{
return false;
}
if ((sMask.charAt(keyCount+1) != '#') && (sMask.charAt(keyCount+1) != 'A' ) && (sMask.charAt(keyCount+1) != '~' ))
{
field.value = field.value + KeyTyped + sMask.charAt(keyCount+1);
return false;
}
if (sMask.charAt(keyCount) == '*')
return true;
if (sMask.charAt(keyCount) == KeyTyped)
{
return true;
}
if ((sMask.charAt(keyCount) == '~') && isNumeric_plusdash(KeyTyped))
return true;
if ((sMask.charAt(keyCount) == '#') && isNumeric(KeyTyped))
return true;
if ((sMask.charAt(keyCount) == 'A') && isAlpha(KeyTyped))
return true;
if ((sMask.charAt(keyCount+1) == '?') )
{
field.value = field.value + KeyTyped + sMask.charAt(keyCount+1);
return true;
}
return false;
}
function getTarget(e) {
// IE5
if (e.srcElement) {
return e.srcElement;
}
if (e.target) {
return e.target;
}
}
function getKeyCode(e) {
//IE5
if (e.srcElement) {
return e.keyCode
}
// NC5
if (e.target) {
return e.which
}
}
function isNumeric(c)
{
var sNumbers = "01234567890";
if (sNumbers.indexOf(c) == -1)
return false;
else
return true;
}
function isNumeric_plusdash(c)
{
var sNumbers = "01234567890-";
if (sNumbers.indexOf(c) == -1)
return false;
else
return true;
}
function isAlpha(c)
{
var lCode = c.charCodeAt(0);
if (lCode >= 65 && lCode <= 122 )
{
return true;
}
else
return false;
}
function isPunct(c)
{
var lCode = c.charCodeAt(0);
if (lCode >= 32 && lCode <= 47 )
{
return true;
}
else
return false;
}

If this was an aspx page, they were probably using the AJAX Control Toolkit MaskedEdit Extender. There is also the Masked Input plugin for jQuery.

Related

To allow the user to insert date in dd/mm/yyyy format in text-box

Friends ,I have a text box for date to be inserted by the user but i want it to allow user to insert only "dd" ,"mm" and "yyyy" values ,slashes(/)should be already present and as soon as the user inserts "dd" values the pointer should move directly behind the slash for "mm" value and on pressing backspace it should delete the "mm" or "dd "values not the slashes(/).
Here is what i have tried but it does not give me the desired result-
function dateCheck(){
var d_value=$("#pdate").val();
if(d_value.length =="2" || d_value.length =="5")
{
$('#pdate').val($('#pdate').val()+"/");
}
}
html code-
Date:<input type="text" name="p_date" id="pdate" onkeydown="dateCheck()" placeholder="DD/MM/YYYY" required />
There's probably plugins out there, but nobody's been too forthcoming with any. Here's something I've knocked up during my lunch break :).
It's not perfect, and could be improved with some tweaking. For example, highlighting multiple characters for deletion is a bit screwy, but hopefully it's not a bad starter for 10. Credit to this post for getting/setting the caret position. Also, it does allow invalid dates right now - 12/34/5678. It wouldn't be too difficult to sort that out. I might stick something on Git and finish it off when I get home.
I've hard-coded it for dd/mm/yyyy format, but, again, with improvments, it could use the user locale.
$.fn.textboxDatePicker = function() {
var _getCaret = function(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(), rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
};
var _setCaretPosition = function(elem, caretPos) {
if (caretPos == 2 || caretPos == 5) {
caretPos++;
}
if (elem != null) {
if (elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
} else {
if (elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
}
else elem.focus();
}
}
};
$(this).val('dd/mm/yyyy');
$(this).on("keydown", function(e) {
var keyCode = e.which || e.charCode || e.keyCode;
var key = String.fromCharCode(keyCode);
// arrows, home, end
if ([35, 36].indexOf(keyCode) > -1) {
return true;
}
if (keyCode == 37) {
var newCaretPos = _getCaret(this) - 1;
if ([2, 5].indexOf(newCaretPos) > -1) {
_setCaretPosition(this, newCaretPos - 1);
return false;
}
return true;
}
if (keyCode == 39) {
var newCaretPos = _getCaret(this) + 1;
if ([2, 5].indexOf(newCaretPos) > -1) {
_setCaretPosition(this, newCaretPos + 1);
return false;
}
return true;
}
// backspace
if (keyCode == 8) {
var text = this.value;
var caret = _getCaret(this);
if (caret == 3 || caret == 6) {
caret = caret - 2;
} else {
caret--;
}
if (caret < 0) {
return false;
}
var output = text.substring(0, caret);
key = 'd';
if (caret > 2) {
key = 'm'
};
if (caret > 4) {
key = 'y'
};
this.value = output + key + text.substring(caret + 1);
_setCaretPosition(this, caret);
return false;
}
if (/[0-9]/.test(key)) {
var text = this.value;
var caret = _getCaret(this);
if (caret > 9) {
return false;
}
var output = text.substring(0, caret);
this.value = output + key + text.substring(caret + 1);
_setCaretPosition(this, caret + 1);
}
return false;
});
};
$('.date').textboxDatePicker();
UPDATE
Might be overthinking this. Could you just use 3 separate boxes and style them to look like one, with a little JS to sort out focusing between them?
https://jsfiddle.net/w9by2350/3/
MUCH cleaner!
Try it
function datecheck(){
value=$(#input_id).val();
if(value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/){
return true;
}else{
alert("not valid format")
}
}

Number validation along with decimals in key press event

I am doing validation of number except on case. I am doing validation in key press event.
This is the process how am doing my validation..
Output length = Integral + decimals
Example: Integral = 5, decimals = 3
If user enter five digits then am not allowing to enter 6th digit. (i.e. 12345).
But if he type '.' then after am allowing to 3 decimals (i.e. 12345.678). This is working perfectly.
Am facing the issue with below case.
If user enter 1.234 then he navigating to before '.' place using arrows or by mouse click, then user unable to enter another digit. Because I am checking either the integral part or decimal part match the length then I am returning false.
Can any one help me out this. I can do with key up event, but I am trying to achieve this by key press event only. Is there any way to get the position where user entering the digit, if yes then I can get one solution.
var integral = 5, decimals = 3;
//below code in the key press event
if ([8, 9, 13, 37, 39,46].indexOf(e.keyCode) != -1) {
return true;
} else if (e.keyCode == 190 && !e.shiftKey && decimals) {
_value = $(this).val();
if (_value.indexOf('.') != -1) {
return false;
}
return true;
} else if (48 >= e.keyCode || e.keyCode <= 57) {
_value = $(this).val();
if (decimals) {
_value = _value.split('.');
if (_value[0].length == integral || (_value[1] || '').length == decimals) {
return false;
}
return true;
} else {
if (_value.length == integral) {
return false;
}
return true;
}
}
return false;
I used selectionEnd for getting position of where user is typing the digit. Using that I did it.
var evt = e.target || e.srcElement;
_value = $(evt).val();
if ([8, 9, 13, 37, 39, 46].indexOf(e.keyCode) != -1) {
return true;
}
else if (e.keyCode == 190 && !e.shiftKey && decimals) {
if (_value.indexOf('.') != -1) {
return false;
}
return true;
}
else if (48 >= e.keyCode || e.keyCode <= 57) {
if (decimals) {
var isHavingDot = false;
var dotPosition = '';
if (_value.indexOf('.') != -1) {
isHavingDot = true;
dotPosition = _value.indexOf('.')
}
var length = _value.length;
if (isHavingDot) {
_value = _value.split('.');
if (evt.selectionEnd <= dotPosition) {
if (_value[0].length >= integral) {
return false;
}
}
else if ((_value[1] || '').length >= decimals) {
return false;
}
}
else {
if (_value.length >= integral) {
return false;
}
}
return true;
}
else {
if (_value.length == integral) {
return false;
}
return true;
}
}
return false;
If you already know how to do it with the keyup event, then you should be able to take that code and insert it into the keypress handler and implement it on the value that would be in the input if you pass the value through.
For example (I assume your validation works like in the example):
$("#myinput").keypress(function (e) {
//first figure out what the value would be if the keypress were passed through
var key=(e.which) ? e.which : e.keyCode;
var inputvalue=String.fromCharCode((96 <= key && key <= 105)? key-48 : key)
var caretPos = document.getElementById("myinput").selectionStart;
var currentvalue=$("#myinput").val();
var outputstring=currentvalue.substring(0, caretPos) + inputvalue + currentvalue.substring(caretPos);
//allow decimals through
if (outputstring===".") {
e.preventDefault();
$("#myinput").val("0.");
return false;
}
//cancel keypress if they string already has a decimal
if(key===46) return (outputstring.split(".").length - 1)>2;
//now perform the truncation and validation
e.preventDefault();
var outputvalue=parseFloat(outputstring);
var decpart=Math.trunc((outputvalue- parseInt(outputvalue)) * 1000)/1000;
var intpart=Math.floor(outputvalue);
//perform your test on the output value here - only need to test the integer part, since the decimal part is truncated
var outputtest=String(intpart).length<=5;
if (outputtest){
//insert the value if it looks okay
$("#myinput").val(intpart+decpart);
}
return false;
});

Validating numeric values using JavaScript

I have the following code. It works fine for blank fields, but it doesn't catch the other numeric exceptions. What am I doing wrong?
function validateForm() {
var a = document.forms["Form"]["percentage"].value;
var b = document.forms["Form"]["minutes"].value;
if (a == null || b == null || a == "" || b == "") {
alert("Please Fill All Required Field");
return false;
} else if (isNan(a) == true || isNan(b) == true) {
alert("Please enter valid numeric values");
return false;
} else if (parseInt(a) > 100) {
alert("Percentage can't exceed 100");
return false;
} else if (parseInt(b) < 0 || parseInt(a) < 0) {
alert("Values can't be negative");
return false;
}
}
Change this line:
else if((isNan(a)==true) ||(isNan(b)==true)){
to this:
else if (isNaN(a) || isNaN(b)) {
as the function is named #isNaN(). Using == true in conditionals is quite redundant, so I removed them.
I have also made a fiddle for you. It contains the fixed code, and it is working well.

how to give validation in javascript where only numbers are allowed to enter in prompt box?

var ratioChange = prompt('Are you sure to change seller ration of this user?');
if(ratioChange != "")
{
$('#clsdywusers_hdnaction').val("SET_SELLER_RATIO");
$('#clsdywusers_seller_ratio').val(ratioChange);
}
else
{
alert('Please enter seller ratio.');
return false;
}
Now here what I want is that I only want to allow users to write digits in prompt box.Please help.
Use javascript input keypress event and check for every typed character if it's a number or not:
function is_numeric(val){
if(val > 47 && val < 58) return true;
else return false;
}
$(".your_input").keypress(function(e){
switch(e.which){
// exclude left and right navigation arrows from check
case 0: case 8:break;
default:
if(is_numeric(parseInt(e.which))) return true;
else{
return false;
}
}
});
Update: with prompt
var ratioChange = prompt('Are you sure to change seller ration of this user?');
if(ratioChange != "" && is_number(ratioChange))
{
$('#clsdywusers_hdnaction').val("SET_SELLER_RATIO");
$('#clsdywusers_seller_ratio').val(ratioChange);
}
else
{
alert('Please enter seller ratio.');
return false;
}
function is_numeric(val){
if(val > 47 && val < 58) return true;
else return false;
}
function is_number(val){
var value= new String(val), singleNumber;
for(var i=0; i < value.length; i++){
singleNumber = 48 + parseInt(value[i]);
if(!is_numeric(singleNumber)) return false;
}
return true;
}
JSBIN

javascript validation for allow -1 and all positive numbers in text box

I am trying to validate a text box to allow all positive numbers including -1 in it.
i tried this, which will work for allowing only positive numbers
function allownumbers(e, txtBox) {
var key;
key = (e.keyCode) ? e.keyCode : e.charCode;
if (e.charCode == 0) {
return true;
}
if ((key < 48 || key > 57) && (key != 46) && (key != 44)) {
return false;
}
if (key == 46) {
if ((txtBox.value).indexOf('.') != -1) {
return false;
}
}
if (key == 44) {
if ((txtBox.value).indexOf(',') != -1) {
return false;
}
}
return true;
}
But how to allow -1(only) with all positive numbers
Thanks in advance
Instead of preventing keystrokes, why not validate and sanitize the input? Maybe something like this:
function allownumbers(e, txtBox) {
var val = parseInt(txtBox.value);
if(!val || val < -1) {
val = 0; // invalid value, reset to zero
}
txtBox.value = val;
}

Categories