I tried to research the answer to this question but I'm lost. I am trying to make a one search bar that automatically puts a dash in the phone number. I've solved that.
The next part is the challenging part. How can I make it always do XXX-XXX-XXXX, even if the characters pasted were something like 555 555 1212 or 555---555-1212, where it will only reel back the number and output with 555-555-1212. It shouldn't count the spaces or extra dashes as a character.
I found: http://www.jotform.com/answers/15202-can-I-add-script-to-my-form-that-will-automatically-add-hyphens-in-between-the-3-digit-area-code-and-also-the-3-digit-prefix
I changed it just a bit by adding:
<SCRIPT LANGUAGE="JavaScript">
function addDashes(f)
{
f.value = f.value.slice(0,3)+"-"+f.value.slice(3,6)+"-"+f.value.slice(6,15);
}
</SCRIPT>
<input id="input_4" class="form-textbox" maxlength="15" name="atn" size="25" onBlur='addDashes(this)' />
Right now, this works only if the user puts 5555555555 and automatically turns it into 555-555-5555. I'm trying to figure out how to take something like 5-55555-5555 and turn it into 555-555-5555. Currently, it makes it 5-5-555-5-5555.
See my dilemma? lol. It can't be php or any server side scripting as this must be able to run on a desktop.
Resolution:
<SCRIPT LANGUAGE="JavaScript">
function addDashes(f)
{
f.value = f.value.replace(/\D/g, '');
f.value = f.value.slice(0,3)+"-"+f.value.slice(3,6)+"-"+f.value.slice(6,15);
}
</SCRIPT>
First, clean your input by deleting all chars that are not numbers (ref.: Regex to replace everything except numbers and a decimal point)
Then, you put your dashes.
function addDashes(f)
{
f_val = f.value.replace(/\D[^\.]/g, "");
f.value = f_val.slice(0,3)+"-"+f_val.slice(3,6)+"-"+f_val.slice(6);
}
I have a strong tendency to treat phone numbers as a straight string of 10 digits with no formatting (so I can apply formatting to them on-the-fly, as needed and so searching and comparison is simpler), although that may change if I ever have to deal with international phone numbers. If all you're dealing with is US phone numbers, this will work nicely (formats it as it's typed):
function addDashes(f) {
var r = /(\D+)/g,
npa = '',
nxx = '',
last4 = '';
f.value = f.value.replace(r, '');
npa = f.value.substr(0, 3);
nxx = f.value.substr(3, 3);
last4 = f.value.substr(6, 4);
f.value = npa + '-' + nxx + '-' + last4;
}
Here's a fiddle: http://jsfiddle.net/EYuk5/
transform with string method replace
let phone = '0884332212'.replace(/^(\d{3})(\d{3})(\d{4})/, '$1-$2-$3')
console.log(phone)
// => 088-433-2212
I did this
function addDashesToNumber(number){
const numWithoutDashes = number.replace(/[^0-9]/g, '')
if(numWithoutDashes.length > 10) return number.slice(0, -1)
const dashPlaces = [3, 6]
return numWithoutDashes
.split('')
.reduce((acc, curr, i) => dashPlaces.includes(i) ? [...acc, '-', curr] : [...acc, curr], [])
.join('')
}
Try this:
function dashedNumber(value){
const afterIndices = [3,6,8];
const length = value.length;
let newValue = ''
for(let i=0; i<length; i++){
if(afterIndices.includes(i))
newValue+='-'
newValue+=value[i];
}
return newValue;
}
Here's a fiddle: https://jsfiddle.net/v9gq5jkw/.
<input id="phone">
function phone_formatting(ele, restore) {
var new_number,
selection_start = ele.selectionStart,
selection_end = ele.selectionEnd,
number = ele.value.replace(/\D/g, '');
if (number.length > 2) {
new_number = number.substring(0, 3) + '-';
if (number.length === 4 || number.length === 5) {
new_number += number.substr(3);
} else if (number.length > 5) {
new_number += number.substring(3, 6) + '-';
}
if (number.length > 6) {
new_number += number.substring(6);
}
} else {
new_number = number;
}
ele.value = (new_number.length > 12) ? new_number.substring(0, 12) : new_number;
if (new_number.slice(-1) === '-' && restore === false &&
(new_number.length === 8 && selection_end === 7) ||
(new_number.length === 4 && selection_end === 3)) {
selection_start = new_number.length;
selection_end = new_number.length;
} else if (restore === 'revert') {
selection_start--;
selection_end--;
}
ele.setSelectionRange(selection_start, selection_end);
}
function phone_number_check(field, e) {
var key_code = e.keyCode,
key_string = String.fromCharCode(key_code),
press_delete = false,
dash_key = 189,
delete_key = [8, 46],
direction_key = [33, 34, 35, 36, 37, 38, 39, 40],
selection_end = field.selectionEnd;
if (delete_key.indexOf(key_code) > -1) {
press_delete = true;
}
if (key_string.match(/^\d+$/) || press_delete) {
phone_formatting(field, press_delete);
} else if (direction_key.indexOf(key_code) > -1) {} else if (dash_key === key_code) {
if (selection_end === field.value.length) {
field.value = field.value.slice(0, -1)
} else {
field.value = field.value.substring(0, (selection_end - 1)) + field.value.substr(selection_end)
field.selectionEnd = selection_end - 1;
}
} else {
e.preventDefault();
phone_formatting(field, 'revert');
}
}
document.getElementById('phone').onkeyup = function(e) {
phone_number_check(this, e);
}
Beside adding dashes, you will need to deal with the position of the cursor, especially in case of deletion.
This AMD module does exactly that: https://github.com/whenyoubelieve2014/us-telephone-input
Related
I have to format an account number input field like below:
Desired format: 123456 1234 12 1
But, the regex which I wrote formats the text field as below:
Current format: 1234 1234 1234 1
Can someone please help me with the correct regex or logic to implement this?
function cc_format(value) {
var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
var matches = v.match(/\d{4,13}/g);
var match = matches && matches[0] || ''
var parts = []
for (i = 0, len = match.length; i < len; i += 4) {
parts.push(match.substring(i, i + 4))
}
if (parts.length) {
return parts.join(' ')
} else {
return value
}
}
onload = function() {
document.getElementById('account-number').oninput = function() {
this.value = cc_format(this.value)
}
}
<form>
<div>AccountNumber</div><br/>
<input id="account-number" value="" placeholder="123456 1234 12 1">
</form>
You can get groups of 6, instead of groups of 4, then, as soon as your second group gets over 4 characters long, you can insert a space at the desired position. Here's a proof of concept:
function cc_format(value) {
var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
var matches = v.match(/\d{6,13}/g);
var match = matches && matches[0] || ''
var parts = []
for (i = 0, len = match.length; i < len; i += 6) {
parts.push(match.substring(i, i + 6))
}
if (parts.length > 1 && parts[1].length > 4) {
parts[1] = [parts[1].slice(0, 4), ' ', parts[1].slice(4)].join('');
}
if (parts.length) {
return parts.join(' ')
} else {
return v
}
}
onload = function() {
document.getElementById('account-number').oninput = function() {
this.value = cc_format(this.value)
}
}
<form>
<div>AccountNumber</div><br/>
<input id="account-number" value="" placeholder="123456 1234 12 1">
</form>
A slightly more elegant solution would be to use .slice() and .join() for the whole thing, which cleans up the code nicely. Here's an example:
function cc_format(value) {
var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '');
if (v.length > 6)
v = [v.slice(0, 6), ' ', v.slice(6)].join('');
if (v.length > 11)
v = [v.slice(0, 11), ' ', v.slice(11)].join('');
if (v.length > 14)
v = [v.slice(0, 14), ' ', v.slice(14)].join('');
if (v.length > 16)
v = v.slice(0, 16);
return v;
}
onload = function() {
document.getElementById('account-number').oninput = function() {
this.value = cc_format(this.value)
}
}
<form>
<div>AccountNumber</div><br/>
<input id="account-number" value="" placeholder="123456 1234 12 1">
</form>
You can use following code, to format the code properly when user is typing. It works dynamically.
const normalize = elem => {
let value = elem.target.value;
const onlyNums = value.replace(/[^\d]/g, '');
if (onlyNums.length <= 6) {
return onlyNums;
} else if (onlyNums.length <= 10) {
return `${onlyNums.slice(0, 6)} ${onlyNums.slice(6)}`;
} else if (onlyNums.length <= 12) {
return `${onlyNums.slice(0, 6)} ${onlyNums.slice(6, 10)} ${onlyNums.slice(10, 12)}`;
}
return `${onlyNums.slice(0, 6)} ${onlyNums.slice(6, 10)} ${onlyNums.slice(10, 12)}
${onlyNums.slice(12, 13)}`;
};
const input = document.getElementById('input');
input.addEventListener('input', (e) => e.target.value = normalize(e));
<input type='text' id='input' value=''>
Bouncing my head off the wall here trying to figure out a better way to handle this. I have a large input value which has three checks to check the sum of certain parts of the string in order to validate it. I'm using three try/catch blocks in one function to run the check right now and it seems to be working except for the final validation check which always seems to return true. What I'm wondering is a) is this a good method to use, b) is there a cleaner way to do this with for loop and c) why my final check is not doing anything. Any help is appreciated. I have access to jQuery and Underscore.js if that helps but I have not worked much with underscore. I made a fiddle here:
Sample Fiddle
window.onkeyup = keyup;
var number;
function keyup(e) {
number = e.target.value;
$('#numberValue').text(number);
// must be 10 characters long
if (number.length !== 30) {
return false;
}
number = "" + (number || "");
// run the checksum
var valid = false;
try {
var sum = (parseInt(number[0]) * 7) +
(parseInt(number[1]) * 3) +
(parseInt(number[2])) +
(parseInt(number[3]) * 7) +
(parseInt(number[4]) * 3) +
(parseInt(number[5])) +
(parseInt(number[6]) * 7) +
(parseInt(number[7]) * 3) +
(parseInt(number[8]));
alert(((sum % 10).toFixed(0)));
var checkDigit = ((sum % 10).toFixed(0));
if ((number[9]) === ("" + checkDigit)) {
alert('Our Checkdigit is valid', checkDigit);
valid = true;
}
} catch (e) {
alert('Fail for check 1!');
valid = false;
}
try {
var sum2 = (parseInt(number[13]) * 7) +
(parseInt(number[14]) * 3) +
(parseInt(number[15])) +
(parseInt(number[16]) * 7) +
(parseInt(number[17]) * 3) +
(parseInt(number[18]));
alert(((sum2 % 10).toFixed(0)));
var checkDigit2 = ((sum2 % 10).toFixed(0));
if ((number[19]) === ("" + checkDigit2)) {
alert('Our Checkdigit2 is valid', checkDigit2);
valid = true;
}
} catch (e) {
alert('Fail for check 2!');
valid = false;
}
try {
var sum3 = (parseInt(number[21]) * 7) +
(parseInt(number[22]) *3) +
(parseInt(number[23])) +
(parseInt(number[24]) * 7) +
(parseInt(number[25]) * 3) +
(parseInt(number[26]));
alert(((sum3 % 10).toFixed(0)));
var checkDigit3 = ((sum3 % 10).toFixed(0));
if ((number[27]) === ("" + checkDigit3)) {
alert('Our Checkdigit3 is valid',checkDigit3);
valid = true;
}
} catch (e) {
valid = false;
}
alert('All Good DUde!');
return valid;
}
Here is the way to do it.
I have not thrown any error, only error can be if the number is not parseable and so you can throw it if you like else if your sum checks can validate that should be good enough
window.onkeyup = keyup;
var number;
function keyup(e) {
number = e.target.value;
$('#numberValue').text(number);
// must be 10 characters long
if (number.length !== 30) {
return false;
}
number = "" + (number || "");
var valid = false;
//try{
var sum1 = returnSum(number,[0,1,2,3,4,5,6,7,8],[7,3,1,7,3,1,7,3,1]);
var sum2 = returnSum(number,[13,14,15,16,17,18],[7,3,1,7,3,1]);
var sum3 = returnSum(number,[21,22,23,24,25,26],[7,3,1,7,3,1]);
/*
//only if you are throwing err
}catch(e){
valid = false;
}
*/
if (number[9] === sum1 && number[19] === sum2 && number[27] === sum3) {
console.log(sum1 +'|' + sum2 + '|' + sum3);
valid = true;
}
console.log('All Good DUde!');
return valid;
}
function myParse(n){
return (isNaN(parseInt(n,10))) ? -1 : parseInt(n,10);
}
function returnSum(n,ind,mul){
var acc = 0;
var pNum = 0;
for(var i=0; i<ind.length; i++){
pNum = myParse(n[ind[i]]);
if(pNum == -1){
pNum=0;
//throw 'error';//if you really want to throw error on not a number / or your number should fail
}
acc += pNum * mul[i];
}
return (acc%10).toFixed(0)+'';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h3> Sample test number to use -- copy and paste should work </p=h3>
<p>487013675311199070109160101300</p>
<input id="searchTxt" placeholder="add numbers together">
<div id='numberValue'>Number goes here</div>
Cheers. joy
From experience, you may want to separate as much math as possible in your try block. JavaScript has a weird way of handling variables and may not be doing what you think it is.
How to allow only one "." in javascript during Keypress?
I have a code here:
function allowOneDot(txt) {
if ((txt.value.split(".").length) > 1) {
//here, It will return false; if the user type another "."
}
}
I will reiterate what I said in my comment before the answer:
And what if the user pastes in a bunch of periods? What if they edit the javascript in their console to completely ignore this check? Make sure you are handling validation correctly and not making too many simplifications.
Now that we're proceeding at our own risk, here's how you would not allow a user typing more than one . (period) in a textbox:
document.getElementById('yourTextboxIDHere').onkeypress = function (e) {
// 46 is the keypress keyCode for period
// http://www.asquare.net/javascript/tests/KeyCode.html
if (e.keyCode === 46 && this.value.split('.').length === 2) {
return false;
}
}
Working demo
If you really want to allow one dot, even in the event of a user pasting text inside it, you should use keyup, not keypress, and you could keep your last text value in case you need to restore it.
The drawback though, is that the input value will have already been changed, and you will see it getting corrected as you type.
(function() {
var txt = document.getElementById('txt');
var prevValue = txt.value;
function allowOneDot(e) {
var dots = 0;
var length = txt.value.length;
var text = txt.value;
for(var i=0; i<length; i++) {
if(text[i]=='.') dots++;
if(dots>1) {
txt.value = prevValue;
return false;
}
}
prevValue = text;
return true;
}
txt.onkeyup = allowOneDot;
})();
I solved this question for the multipurpose use of decimal, number & alphanumeric field types.
For field types 'number' and 'alphanum', parameter l (lower L) is the string length allowed. For type 'decimal', it specifies the allowed number of decimal places.
function allowType(e, o = 'number', l = false) {
let val = e.target.value;
switch (o) {
case 'alphanum':
if (l) {
val = val.substr(0, l).replaceAll(/[^0-9a-zA-Z]/gmi, '');
} else {
val = val.replaceAll(/[^0-9a-zA-Z]/gmi, '');
}
break;
case 'number':
if (l) {
val = val.substr(0, l).replaceAll(/[^0-9]/gmi, '');
} else {
val = val.replaceAll(/[^0-9]/gmi, '');
}
break;
case 'decimal':
let i = val.search(/\./gmi);
if (val.length === 1) {
val = val.replaceAll(/[^0-9]/gmi, '');
}
if (i >= 0) {
if (l) {
val = val.substr(0, i + 1) + val.substr(i).substr(0, l + 1).replaceAll(/\./gmi, '');
} else {
val = val.substr(0, i + 1) + val.substr(i).replaceAll(/\./gmi, '');
}
}
val = val.replaceAll(/[^0-9.]/gmi, '');
break;
}
e.target.value = val;
}
<input type="text" oninput="allowType(event, 'decimal', 2)" placeholder="decimal">
<input type="text" oninput="allowType(event, 'number', 10)" placeholder="number">
<input type="text" oninput="allowType(event, 'alphanum', 5)" placeholder="alphanumeric">
<input type="text" id="test" onkeyup="floatOnly(this);"/>
<script>
function floatOnly(i){
{
if ((i.value).length > 0){else{i.value = i.value.replace(".." , ".");i.value = i.value.replace("..." , ".");i.value = i.value.replace(/[^0-9\.]/g , "");}}else{i.value = i.value="0";}}<script>
This is my first webpage in which I prompt the user for a phone number to add to a Do Not Call List database. Everything is working so far but I need to add the following, which I can do following the advice in this answer
stripping the input from all characters except digits
validating that the resulting string is 10 digits long
Then, when telling the user that the number was added to the list, I want to present it in the (999) 999-9999 format.
Where should I add all that code? Iside the #{ } block? In JavaScript? Razor?
Check phone number
function IsNumber(s) {
var i, currentCharacter;
for (i = 0; i < s.length; i++) {
// Check that current character is number.
currentCharacter = s.charAt(i);
if (((currentCharacter < "0") || (currentCharacter > "9"))) {
return false;
}
}
// All characters are numbers.
return true;
}
function TestInternationalPhone(strPhone) {
var bracket = 3,
openBracket,
phoneNumberOnly,
phoneNumberDelimiters = "()- ",
validWorldPhoneChars = phoneNumberDelimiters + "+",
minDigitsInIPhoneNumber = 10;
strPhone = SOS.StringHelper.Trim(strPhone);
if (strPhone.length === 0) {
return false;
}
if (strPhone.indexOf("+") > 1) {
return false;
}
if (strPhone.indexOf("-") != -1) {
bracket = bracket + 1;
}
if (strPhone.indexOf("(") != -1 && strPhone.indexOf("(") > bracket) {
return false;
}
openBracket = strPhone.indexOf("(");
if (strPhone.indexOf("(") != -1 && strPhone.charAt(openBracket + 2) != ")") {
return false;
}
if (strPhone.indexOf("(") == -1 && strPhone.indexOf(")") != -1) {
return false;
}
phoneNumberOnly = SOS.StringHelper.StripCharsInBag(strPhone, validWorldPhoneChars);
return (IsNumber(phoneNumberOnly) && phoneNumberOnly.length >= minDigitsInIPhoneNumber);
}
I want to make user control to get number like this:
125.00
125
125.27
125.20
1231545.25
2566.66
I have tried with mask textbox but its length can be anything.
I have used textbox with Javascript that accepts a number
like this:
click here
If a Javascript plugin is available for this let me know,
or any code to accept value in price format.
Restrict user to insert only number and two decimal spaces while entering.
If number is not well formatted then cut and format number after text change.
Like if 125.2 then 125.20 or if 125 then 125.00 or 135156. then 135156
I have search on internet but no plugin or script was found for this.
I have a plugin like numeric.js but it doesn't restrict decimal spaces.
Post if any Javascript available.
I don't want to do validation to check for entered values; I want to accept values with restriction.
Please help me.
You can use Ajax Control Toolkit MaskedEdit control:
MaskedEdit is an ASP.NET AJAX extender that attaches to a TextBox control to restrict the kind of text that can be entered. MaskedEdit applies a "mask" to the input that permits only certain types of characters/text to be entered. The supported data formats are: Number, Date, Time, and DateTime. MaskedEdit uses the culture settings specified in the CultureName property. If none is specified the culture setting will be the same as the page: English (United States).
Sample Code:
<ajaxToolkit:MaskedEditExtender
TargetControlID="TextBox2"
Mask="9,999,999.99"
MessageValidatorTip="true"
OnFocusCssClass="MaskedEditFocus"
OnInvalidCssClass="MaskedEditError"
MaskType="Number"
InputDirection="RightToLeft"
AcceptNegative="Left"
DisplayMoney="Left"
ErrorTooltipEnabled="True"/>
See Working Demo
I also having same problem.This code has solved my problem.This solution is exactly what u want.It's not only foramt yous decimal number but also will eliminate blank spaces. Try this.As in my condition i was allowing user to enter '+' or '-' so i check for this validation also.
<script type="text/javascript">
function checkforvalidation() {
var txtvalue = document.getElementById('<%=txtspherical.ClientID %>').value;
var leftstr = "";
var rightstr = "";
var tempstr = "";
var operator = "";
txtvalue = txtvalue.replace(/\s/g, '');
document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
if (txtvalue.indexOf(".") != -1) {
leftstr = txtvalue.split(".")[0];
rightstr = txtvalue.split(".")[1];
if (leftstr.indexOf("-") == 0 || leftstr.indexOf("+") == 0) {
operator = leftstr.substr(0, 1);
tempstr = leftstr.substr(1, leftstr.length - 1);
leftstr = ltrim(tempstr, '0');
if (leftstr.length == 0) {
leftstr = '0';
}
if (rightstr.indexOf("-") == -1 || rightstr.indexOf("+") == -1) {
rightstr = ltrim(rightstr, '0');
rightstr = chkdecimalpoints(rightstr);
if (operator != null || operator != "") {
txtvalue = operator + leftstr + "." + rightstr;
}
else {
txtvalue = leftstr + "." + rightstr;
}
document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
}
else {
document.getElementById('<%=txtspherical.ClientID %>').value = "";
}
}
else {
tempstr = leftstr.substr(0, leftstr.length);
leftstr = ltrim(tempstr, '0');
if (leftstr.length == 0) {
leftstr = '0';
}
if (rightstr.indexOf("-") == -1 || rightstr.indexOf("+") == -1) {
rightstr = rtrim(rightstr, '0');
rightstr = chkdecimalpoints(rightstr);
txtvalue = leftstr + "." + rightstr;
document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
}
}
}
else if (txtvalue.indexOf("-") == -1 || txtvalue.indexOf("+") == -1) {
txtvalue = ltrim(txtvalue, '0');
if (txtvalue.length == 0) {
txtvalue = '0';
}
if (operator != null || operator != "") {
txtvalue = operator + txtvalue + ".00";
}
// txtvalue = leftstr + "." + rightstr;
document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
}
else if (txtvalue.indexOf("-") == 0 || txtvalue.indexOf("+") == 0) {
operator = txtvalue.substr(0, 1);
tempstr = txtvalue.substr(1, leftstr.length - 1);
txtvalue = alltrim(tempstr, '0');
if (operator != null || operator != "") {
txtvalue = operator + txtvalue + ".00";
document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
}
}
}
function chkdecimalpoints(rightstr) {
if (rightstr.length == 0) {
rightstr = '00';
return rightstr;
}
else if (rightstr.length == 1) {
rightstr = rightstr + '0';
return rightstr;
}
else if (rightstr.length > 2) {
var tempvar = rightstr.substr(2, 1);
if (tempvar >= 5) {
tempvar = parseInt(rightstr.substr(1, 1)) + 1;
tempvar = rightstr.substr(0, 1) + tempvar.toString();
if (tempvar.length > 2) {
tempvar = tempvar.substr(0, 2);
}
return tempvar;
}
else {
tempvar = rightstr.substr(0, 2);
return tempvar;
}
}
else {
return rightstr;
}
}
function ltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
function alltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+$", "g"), "");
}
</script>
HTML Source:
<asp:TextBox ID="txtspherical" runat="server" OnBlur="javascript:checkforvalidation();">
</asp:TextBox>
function validNumber(input){
input=input.replace(/\s+/g," ").replace(/^\s+|\s+$/g,"");
if( input.match(/\d+\.*\d*/i) ){
input=input.match(/(\d+\.*\d*)/i)[1].replace(/\.$/i, "");
if(!input.match(/\./i)) input+=".00";
if(input.match(/\.(\d+)/i)[1].length<2) input+="0";
return input;
}else{
return "0.00";
}
}