I currently use the script below to take any form of information and pull out the numbers to make a phone number with dashes in it. However, if I accidently click in the field, it puts two dashes in there even though nothing was pasted or typed. Does JS have a way to say ONLY if something is pasted then add dashes? The reason it's a pain is I have 2 search fields, and if I want to use one, the other has to be blank. So if there are 2 dashes in it, I have to delete them out and hit enter in the same field or it will add them again.
I appreciate any help you might have.
<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>
I'd go with something like this:
function addDashes(f) {
f.value = f.value.replace(/(\d{3})-?(\d{3})-?(\d{9})/, '$1-$2-$3');
}
It'll only do something if you have 15 digits there (possibly with dashes already in place).
I'm not quite sure if this is what you need, but this just checks to see if there is actually something there before formatting it:
function addDashes(f)
{
var oldVal = f.value.replace(/\D/g, '');
if (oldVal.length) {
f.value = oldVal.slice(0,3) + "-" + oldVal.slice(3,6) + "-" + oldVal.slice(6,15);
}
}
EDIT:
Based on your comment, I thought it might be helpful to bring up validation. I'm not sure if you are doing anything on the server-side to make sure it is a valid phone number, but it might be helpful to do a little validation so taht you don't add dashes if the user has just typed some spaces.
First, I would remove the non-numeric values before you check the length. I've updated the code above to do that.
Next, I would check against some length. Maybe you want to only add dashes if the number is at least 9 digits long. You can decide that length taht you watn to check against. In that case, you would add:
if (oldVal.length >= 9) { ...
It all depends on if/how you are validating this field.
Related
I have one requirement in form.My form has textbox field "DEA License number".textbox must allow user to enter alphabet only for first two characters and numbers only after two characters.I want to achieve this functionality using javascript.Note:-I dont want validation but avoid user inputting
Have you tried using regex?
Take a look at this post which has a very similar goal: RegEx pattern any two letters followed by six numbers
Try use some of masked textbox.
For example:
https://css-tricks.com/input-masking/
http://digitalbush.com/projects/masked-input-plugin/
You can easily test this with a regex:
function isValid(str) {
return /^[a-zA-Z]{2}\d+$/.test(str);
}
I am not quite sure what you mean by "I dont want validation but avoid user inputting." If you mean that you don't want the user to be able to type an invalid character, this could theoretically be done with an input event handler:
var oldValue = "";
document.getElementById("test").addEventListener("input", function(e) {
var value = e.target.value;
if ((value.length <= 2 && /^[a-zA-Z]*$/.test(value)) || value.length > 2 && /^[a-zA-Z]{2}\d+$/.test(value)) oldValue = value
else e.target.value = oldValue;
})
However, you'd still need to validate it when it's submitted since the user could've entered an incomplete value.
I have a form that has a field that takes what a decimal value. The desired requirements for this decimal are that it be in the form ##.## with two numbers on each side of the decimal point.
I found a regex online that is supposed to validate the decimal, but instead views any input as invalid. Here is the code I have:
function validateDecimal(number)
{
eval("var stringvar=/^[-+]?([0-9]*\\.[0-9]{0,2})|([0-9]+)$/");
return stringvar.test(number);
}
And the call...
var numStr = document.getElementById('Amount');
if (!validateDecimal(numStr)) {
alert("Please enter a valid dollar amount in the form ##.##");
return false;
}
I understand that this regex is not exactly what I'm looking for, but I can't seem to figure out why it views all input as invalid. Does anyone know what I'm doing wrong?
The first problem is that you forgot to grab the actual value of your input:
document.getElementById('Amount').value
The second problem is eval, you don't need it here, you can write it like this:
var stringvar = /^[-+]?([0-9]*\.[0-9]{0,2})|([0-9]+)$/;
And third, here's the regex I propose if your number must always be XX.XX:
/^[+-]?\d\d\.\d\d$/
first off, you shouldn't be using eval like that, it puts unnecessary stress on the client, just do
var regex = /^[-+]?([0-9]*\\.[0-9]{0,2})|([0-9]+)$/;
return regex.test(number);
instead.
And you need to use .value after getElementById('Amount');
Given:
var input_val = $('#field').val();
How do I check whether input_val contains only numbers or commas? The solution must work in the 4 main browers.
/^(\d|,)+$/.test(input_val) will return true as long as input_val only contains digits and/or commas.
Use the following function
function containsNumbersAndCommasOnly(str) {
return /^[0-9,]+$/.test(str);
}
by calling
if (containsNumbersAndCommasOnly(input_val)) {
}
This is a combination of the response from #Adil and a community post answer from a different post. The combination of the two works better than either individually but there are still some issues... 12,12,12 would be valid here so would 1,,,,,,,,,9 as pointed out as #mplungjan.
For my purposes this is as far as I am willing to go but someone good with regex might add a solution that detects for single instances of commas followed but not preceded by a minimum of 3 digits.
if(!(!isNaN(parseFloat(n)) && isFinite(n))){
return /^(\d|,)+$/.test(n);
}else{
return true;
}
I'm looking for a good way to check a number that a user has entered for correct position of optional commas.
For example
1,000,000.00 = correct
1000000 = correct
1,00,000.00 = incorrect
,100,000 = incorrect
So it looks like I need to check to see that there is at least one number to the left and 3 numbers to the right of the comma, or is there a RegEx way to do this?
/^(?:\d+|\d{1,3}(?:,\d{3})*)(?:\.\d+)?$/
What are you going to use this for? Or put another way, why care? Why not just strip out all commas and convert it to a numeric type?
Check out this website: http://blog.stevenlevithan.com/archives/commafy-numbers
Here's the code snippet:
String.prototype.commafy = function () {
return this.replace(/(^|[^\w.])(\d{4,})/g, function($0, $1, $2) {
return $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, "$&,");
});
}
Number.prototype.commafy = function () {
return String(this).commafy();
}
What you can do is replace all commas and then use this code to add in the commas yourself.
Hope that helps.
Here’s a pattern that answers your question. There are also many other number-related patterns there, including ones that are maintainable — something no one ever seems to worry about.
I'm trying to set up a field to prepopulate with a unique set of characters, so that i can automatically generate test accounts. Because of the way the system is set up, the name field must be unique, and must not include numerical characters.
I put together this selenium code, and it works 99% of the way, but leaves extra garbage characters at the end of the good code.
javascript{stringtime='';
nowtime=new Date().getTime().toString();
for ( var i in nowtime )
{ stringtime+=String.fromCharCode(parseInt(nowtime[i])+65 ); };
'test' + stringtime + '\0'}
Result:
testBCEBBJCBFBBAI + a bunch of characters that won't copy into here. They look like 4 zeros in a box.
Thanks in advance for the help.
Excluding the '\0' character at the end, which shows up at a ?, and within Selenium, I think it's javascript engine is having trouble processing the for(var i in nowtime).
Try it like this:
javascript{
stringtime= '';
nowtime=new Date().getTime().toString();
for(var i = 0; i < nowtime.length; i++){
stringtime += String.fromCharCode(parseInt(nowtime[i])+65);
}
stringtime;
}
Those characters are ones that are outside the standard ASCII that your font can't reproduce. Those numbers signify which character it is. If its 4 zeros, its that \0 char you are putting on at the end. I don't know the language, but it doesn't look like you need that.
Also your random number generator is a bit flawed. Have a look here:
http://www.mediacollege.com/internet/javascript/number/random.html