I have a couple of forms with input fields of type number don't seem to have any validation applied by Safari (on Mac OS X Mavericks). That is, if one types letters and hits submits, in every browser a little message appears that you need to put numbers in the field - except Safari. Oh, and Firefox too on this platform.
So, I decided I needed to add validation to my JavaScript code that is handling these form values. I put in a regular expression to reject anything that is not a single-digit number:
if ( !/^([0-9])$/.test(value) ) {
alert ("Please enter a number");
return;
}
In Firefox, this behaves as I hoped. If you enter any letters, or anything other than a single digit, the alert is displayed.
On Safari, if you enter two or more digits, the alert is displayed too, but if you enter non-digit characters, it is not. It acts as if it happily accepts the input, but if I then further add an alert box in an else block below the above to show me what value is, that doesn't get displayed either. There are no errors in the JavaScript console. It's like it just does nothing.
I've stared at the regex a bunch, though it's about as simple as it can be. I'm pretty flummoxed. Any ideas, anyone?
I don't really like regexes. They are always so error prone and you sometimes don't consider all possible matches. Why don't you use something like this:
if (parseInt("15", 10) !== NaN)
alert("is numeric");
else
alert("please enter a number");
Your regex tests true for a string that is a single digit and false (and enters your negated if condition) otherwise. Must it be only one digit or one or more digits?
Add a + to specify one or more numeric values.
/^([0-9]+)$/
Also do you need or are you using the grouping (parenthesis around the digits)?
/^[0-9]+$/
fiddle
Misc ways to validate integer ..
// Integers including 0: following values will return true (0, 1, 2 .., 65, etc.)
/^(?:0|[1-9]\d*)$/.test(value);
// Integers, zero not allowed
/^[1-9]\d*$/.test(value);
// Test whether the value is an integer or not (+ sign try to cast the value into a number)
if(Number.isInteger(+value)){/* ... */}
User friendly solution ..
Few months ago, I had to format a user input that had to be either an integer or a float number ; Formatting process is triggered on keypress.
This is what I achieved Fiddle here
Allowed formats
.80
0.80
15.80
1500
Hope it will help ..
Related
I am thinking all possibilities that a user can enters into a <input> of type number and using jquery to validate the input.
In the input field, I put in just a simple dot '.'
if($("#timetaken").val() == "")
and this if statement executed with the response saying it is empty. There is a '.' dot in it and logically speaking it should skip this and execute the else that tells us it is not empty.
I also tested with the input "1." that is incomplete with
console.log($("#timetaken").val().toString().indexOf("."));
and it returns -1, which means the '.' is not there and ignored.
The question is there a way to validate these two inputs in an <input> tag of type number?
Thank you.
If you try to test a number input with some non-number characters (like a single dot).. Yes, sure the empty passes.
I would suggest you to use a text input with a regular expression to test the value as you wish. This input type has no strange behavior or restriction and a "regex" can exactly test the value for whatever requirement you have.
That would be (from what I can read from your question) something like:
$("#go").on("click",function(){
var value = $("#test").val();
var regex = /((\d){1,9}\.?\d*)|(\d*\.?(\d){1,9})/; // {1,9} means at least 1 and up to 9 digits.
if(regex.test(value)){
console.log("Value is ok");
}else{
console.log("Value fails.");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test"> <button id="go">Test</button>
So floating numbers or natural numbers are ok.
Nothing else.
Regex tester: regex101.
How do I retain a 0 in the numeric formatted fields when the zero is at the beginning of a number? right now the field drops the 0 and proceeds to display the second number.
For example, in the number field, if i enter "00100", then it displays as "100".
I have written a keystroke script to accept only numbers but I need to limit the numbers to 6 digits
Please help.
function numOnly_ks() {
// Get all of the characters that have been entered in to the field
var value = AFMergeChange(event);
// Do nothing if field is blank
if(!value) return;
// Reject the entry if the entry doesn't match the regular expression
if(!AFExactMatch(/^[0-9 /+]+$/, value)) event.rc = false;
}
One possibility is to add this to the Validate event:
event.value = util.printf("%,106d", event.value) ;
Note: I have not tested it, but it should work. You might have a look at the util.printf() method description in the Acrobat JavaScript documentation.
Do you actually need the field entry to be a numerical value (i.e., do you need to use the value for mathematical purposes)? If not, you can just set the field to be a text entry, which will allow a user to enter numbers as text in the field, and will thus allow the entry of leading zeros. To do this, go to the following menu: Edit>Edit Text & Images>Forms>Edit>[then click on the field you want to edit]>Edit Fields>Show Field Properties>Format>[then set "Select Field Properties" to "None"]. This change will allow a user to enter any characters in the field, so it's not going to be an option for any form owner/creator who needs to limit the field entry parameters/rules for users. But it works as a quick one-off solution to force leading zeros.
I've an HTML field in a form and, using JS and Regex, I must restrict the characters the user can insert in the field. The user of the form can only insert the following characters ( ) * + ^ / X x, and numbers and spaces (when he digits or pastes a different character nothing is written). Is this possible? I need the Regex, I eventually know how to do with JS.
Try this regex
[^\(\)\*+\^/Xx0-9 ]
Here we are trying to find a pattern which contains none of the allowed characters. If you find it this means that the character entered was wrong.
There is no right or wrong answer to this.
Usually it is less expensive to check using the bias of the logic for the particular condition.
If it sounds better saying whats allowed, then use the allowed (positive) character class.
Allowed class: [()*+^/Xx0-9 ], Checks: <space> (-+ /-9 X \^ x
Not allowed class: [^()*+^/Xx0-9 ], Checks: \0-\37 !-' , \- . :-W Y-\] _-w y-\377
Statistically, if %99 of the data enterred were valid, the 'Allowed' class would do less work in that
not every character or range has to be checked.
Where the 'Not-Allowed' class will have to check every range.
In this particular case, the negative class has many more ranges and characters to check, its borderline
more efficient if most of the data were invalid,
With regard to:
[^\(\)\*+\^/Xx0-9 ]
None of those characters need to be escaped inside a set (but it is okay to do so).
If you want to restrict as the user types (this uses jquery methods):
$('#in1').keyup(function (evt) {
var content = $('#in1').val();
$('#in1').val(content.replace(/[^()*+^/Xx0-9]/g, ""));
return true;
});
Where 'in1' is the id of the input.
I need a regex for Javascript that will match a phone number stripped of all characters except numbers and 'x' (for extension). Here are some example formats:
12223334444
2223334444
2223334444x5555
You are guaranteed to always have a minimum of 10 numerical digits, as the leading '1' and extension are optional. There is also no limit on the number of numerical digits that may appear after the 'x'. I want the numbers to be split into the following backreferences:
(1)(222)(333)(4444)x(5555)
The parenthesis above demonstrate how I want the number to be split up into backreferences. The first set of parenthesis would be assigned to backreference $1, for example.
So far, here is what I've come up with for a regex. Keep in mind that I'm not really that great with regex, and regexlib.com hasn't really helped me out in this department.
(\d{3})(\d{3})(\d{4})
The above regex handles the 2nd case in my list of example test cases in my first code snippet above. However, this regex needs to be modified to handle both the optional '1' and extension. Any help on this? Thanks!
Regex option seems perfectly fine to me.
var subject = '2223334444';
result = subject.replace(/^1?(\d{3})(\d{3})(\d{4})(x\d+)?$/mg, "1$1$2$3$4");
alert(result);
if(!result.match(/^\d{11}(?:x\d+)?/))
alert('The phone number came out invalid. Perhaps it was entered incorrectly');
This will say 12223334444 when there is no extension
I expect you want to tweak this out some, let me know how it should be.
If I were you, I would not go with a regular expression for this — it would cause more headaches than it solved. I would:
Split the phone number on the "x", store the last part in the extension.
See how long the initial part is, 9 or 10 digits
If it's 10 digits, check that the first is a 1, slice it off, and then continue with the 9-digit process:
If it's 9 digits, split it up into 3-3-4 and split them into area code, exchange, number.
Validate the area code and exchange code according to the rules of the NANP.
This will validate your phone number and be much, much easier and will make it possible for you to enforce rules like "no X11 area codes" or "no X11 exchange codes" more-easily — you'd have to do this anyway, and it's probably easier to just use plain string manipulation to split it into substrings.
I did a bit more testing and here's a solution I've found. I haven't found a case where this breaks yet, but if someone sees something wrong with it please let me know:
(1)?(\d{3})(\d{3})(\d{4})(?:x(\d+))?
Update:
I've revised the regex above to handle some more edge cases. This new version will fail completely if something unexpected is present.
(^1|^)(\d{3})(\d{3})(\d{4})($|(?:x(\d+))$)
My regex is:
/\+?[0-9\-\ \(\)]{10,22}/g
Is there any existing jQuery functionality that can test if characters entered into a textbox are either numeric, or valid in a number?
Such as
.00 or 0.00, but not 0.00.00 or 0a
What I'd like to do is catch any invalid characters before they appear in the textbox.
If it's not possible with jQuery, what's the best way to approach this?
I know with JavaScript I can test isNaN() and then return false, but that's going to start getting hairy when I have to account for all possible keystrokes.
just use a regex match
$('#formelement').val().match(/[-+]?[0-9]*\.?[0-9]+/)
(excluding selector, everything else is plain javascript)
As noted in comments, since you need to do it for each character inserted you have to consider an empty decimal part valid (eg. /[-+]?[0-9]*\.?[0-9]*/)
Since people in comments forces me to be precise I can suggest you how to work out how to use this matching for your purpose (but so you don't let anything to the OP imagination :( )
You can split the regex in 3 regexs, one for the first part (eventual sign and whole part), one for the first part plus the dot symbol and one for the whole number.
You validation routine should accept the input while it's being written if it matches at least one of the threes regex just described and the validation done at the end should accept just when the last regex is matched (since you are submitting the value and you need it to be correct)
It's a little tricky, since you want to make sure you can enter all numbers left to right, but something like this:
$("input").keyup(function() {
this.value = this.value.match(/[-+]?[0-9]*\.?[0-9]*/);
});
Try it out with this jsFiddle
Note how I'm checking the number from left to right. This means that + must be valid. Also 5. must be valid, or you could never enter 5.0 or +5.
Now the above has some major issue (try the arrow keys).
Here's a slightly more elegant solution that accommodates a default value as well:
$(function() { // <== DOC ready
var prev=""; // Initial value to replace default text with
$("input").click(function () { // Include a select on click
$(this).select(); // if you have a default value
});
$("input").keyup(function() {
if(/^[-+]?[0-9]*\.?[0-9]*$/.test(this.value)) // If number....
prev = this.value; // store it as the fallback
else
this.value = prev; // else go to fallback
});
});
Try it out with this jsFiddle
Example HTML for the above:
<input type="text" value="Enter only a number" />
Note how when you use .test() you have to test from the beginning ^ to the end $.
Seems like a work for regular expressions:
var x = '0.00';
var y = '0.000.00';
x.match(/^[0-9]+\.*[0-9]*$/);
y.match(/^[0-9]+\.*[0-9]*$/); // evaluates to null
You can use a plugin or another separate library to do form validation. An example:
http://www.geektantra.com/2009/09/jquery-live-form-validation/
Regular expressions would also work if you wanted to handle this manually.
I'm using this plugin for my projects:
http://www.texotela.co.uk/code/jquery/numeric/
it's simple but have some bugs with negative values,
anyway it works great for a simple use!
you can you use it like so:
$("input.numericInput").numeric();