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();
Related
I am trying to do a validation on a textbox value with jquery to make sure textbox accepts only alpha numeric values. I am also trying to allow spaces between words. I am not trying to allow spaces to left and right of the sentence in textbox. how can I allow spaces in middle of words in the textbox?
My trails fiddle
$('#dsTest').keyup(function() {
if (this.value.match(/[^a-zA-Z0-9]/g)) {
this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
}
});
You're not going to be able to do it gracefully using only keyup, because while still in the process of typing the sentence, the space you just typed (intending it to be in the middle) is at the end.
Instead, I would do something like this:
$('#dsTest').keyup(function() {
if (this.value.match(/[^a-zA-Z0-9 ]/g)) {
this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');
}
});
$('#dsTest').focusout(function() {
this.value = this.value.trim();
});
Allow spaces to be typed while typing is in progress, and strip the leading and trailing spaces with String.trim() at some reasonable later point. In my example, I use .focusout(), but you could also just trim when consuming the value.
This is an example of a broader category of validation problems in which testing WHILE input is being entered prevents the user from entering a value that would have been legal once they were done - because entering the value one character at a time requires the value to temporarily have an invalid state. There are two main ways of handling that problem:
Don't test for validation until the user has finished inputting the value
Flag invalid values rather than altering them
You can also combine the two - for instance, highlighting the field while the user is typing to show that the current value is invalid, and then also fixing the value to make it valid if they leave the field while the invalid value is still present.
In pure regex this should work /^[a-zA-Z0-9]+[a-zA-Z0-9\s]*[a-zA-Z0-9]+$/g. Note that this would requires at least 2 characters in the value. If you want to also allow it to be blank then you could do /^([a-zA-Z0-9]+[a-zA-Z0-9\s]*[a-zA-Z0-9]+|)$/.
With all that said, it is prob better usability-wise to just trim the value, as mentioned by other answers, since that does not stop the user from moving forward if they accidentally add a leading or trailing space.
I wrote a fairly simple regular expression to detect when a string looks like it could be an email:
var looksLikeEmail = /^\S+#\S+\.\S+$/gi;
I'm using Knockout and the string being tested is the value of a textarea.
Essentially, say we have the value of the textarea in a variable text. This value was, for example, the typed in value abc#example.com.
What's odd, is it seems like, even though text === text.trim(), looksLikeEmail.test(text) returns true, but looksLikeEmail.test(text.trim()) returns false.
On the other hand, if I manually create the string var test2 = 'abc#example.com', it does not have this issue.
This seems to indicate to me that the textarea is inserting some odd characters or something... that .trim() is doing something weird with. But test.length === test2.length and test.length === test.trim().length
Does anyone know how to make this behave correctly?
I've written up a jsfiddle to quickly demonstrate the behavior...
If you go to the fiddle and try typing in an email... you will see the problem. another weird behavior: add a space after the email, then remove it. /confused
Any help is much appreciated. Thanks.
.test(), just like .exec() will remember the last index of a match when using a global regex, and try to match from it onward, failing on the second call. Just remove the /g option from your regex - it doesn't make sense to have /g in a non-multiline regex which matches beginning and end.
See this fiddle: http://jsfiddle.net/5vTc7/
If you open the console, you can see that the regular expression in the pattern attribute ((?=^[0-9]*(\.[0-9]+)?$)(?=.*[1-9])) works as expected from JS, but when you enter anything in the input and try to submit, it fails.
In case there's something wrong with my regular expression, I'm simply trying to limit it to numbers greater than 0. I'd like to use the number input (i.e., <input type="number"/>), but I can't, because it doesn't allow you to format the values (e.g., it will display 0.00000001 as 1e-8, which is undesirable).
I am clueless here. Is there something I'm missing? Why doesn't this work?
When you use the pattern with anchors, as specified in The pattern attribute, it will fail with Javascript as well
var pattern = '^(?=^[0-9]*(\.[0-9]+)?$)(?=.*[1-9])$';
var reg = new RegExp(pattern);
console.log(reg.test('1.0')); // will fail
console.log(reg.test('0.0')); // will fail
See modified JSFiddle
If you want to limit the input to non-null numbers, you can use
\d*[1-9]\d*(?:\.\d*)?|\d+\.\d*[1-9]\d*
This pattern requires at least one non-null digit either before or after the decimal point.
See JSFiddle
You can try this pattern:
^(?:0+\.0*[1-9][0-9]*|0*[1-9][0-9]*(?:\.[0-9]+)?)$
I know that SO is not a code generator, but I break my head and I'll got mad with this RegExp.
I've <input /> type text, in a HTML <form />. The input is automatically filled when the user double-click on elements in a specific list.
This event will generate string like "[text:number]" or "[text:number:text]", and place it at the cursor position in my <input /> field.
The first goal of this process is to construct a mathematic formula structure. I mean, the generated strings between brackets will insert elements, then I want to allow the user to put only numbers and operators.
I've tried to bind the keydown event, and test the char with String.fromCharCode(e.which); but for the keys "+" or "-" (and other operators) this function returns alphabeticals chars. Without success.
Then, I've finally decided to use the keyup event, then use a RegExp to replace the <input /> value.
$("#inputID").keyup(function(){
var formule = $(this).val();
var valid_formule = formule.replace(CRAZY_REGEXP,'');
$(this).val(valid_formule);
});
So, my question is as follows :
How construct a javascript RegExp, to remove all chars which are not between brackets, and which are differents of ()+-*/,. and numbers.
An example :
"a[dse:1]a+a[dse:5]a+a[cat:5:sum]a+(a10a/5,5)!"
will become
"[dse:1]+[dse:5]-[cat:5:sum]+(10/5,5)"
I'm open to another way to achieve my goal if you have some ideas.
Thanks !
You may try something like this:
var re = /[^\]\d\(\)+\-*\/,.]+(?=[^\[\]\(\)]*(?:\[|\(|$))/g;
$("#inputID").keyup(function(){
this.value = this.value.replace(re, "");
});
Keep in mind, though, that you have to be sure that the parenthetical structure is coherent with your syntax.
Advice: use RegExr to test your regular expressions, but remember that it's more powerful than Javascript regex support.
I have this RegEx that validates input (in javascript) to make sure user didn't enter more than 1000 characters in a textbox:
^.{0,1000}$
It works ok if you enter text in one line, but once you hit Enter and add new line, it stops matching. How should I change this RegEx to fix that problem?
The problem is that . doesn't match the newline character. I suppose you could use something like this:
^[.\r\n]{0,1000}$
It should work (as long as you're not using m), but do you really need a regular expression here? Why not just use the .length property?
Obligatory jwz quote:
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.
Edit: You could use a CustomValidator to check the length instead of using Regex. MSDN has an example available here.
What you wish is this:
/^[\s\S]{0,1000}$/
The reason is that . won't match newlines.
A better way however is to not use regular expressions and just use <text area element>.value.length
If you just want to verify the length of the input wouldn't it be easier to just verify the length of the string?
if (input.length > 1000)
// fail validation