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.
Related
I have this JavaScript code that only allows users to enter letters and white space. If I allow that, the user can now enter the name as white space only and it will go to the database. Is there a way to prevent the user from entering white space only and force them to add letters?
And an optional question, can I prevent the user from entering two white spaces?
<script>
function lettersOnly(input) {
var regex = /[^a-z & " "]/gi;
input.value = input.value.replace(regex, "");
}
</script>
<input id="fullname" placeholder="fullname" onkeyup="lettersOnly(this)">
You could just leave your code as is and when the user submits the form, you get rid of any whitespace. Something like:
string.replace(/\s/g,'')
The \s character matches ANY number of whitespaces, so that also solves your problem of preventing the user from entering two or more whitespaces.
However, if having whitespace in the name is a real problem, you should consider doing this on the back-end, to prevent the possibility of people bypassing your regex replace and inserting unwanted values into the DB.
Try this regex, and it will allow for one whitespace only. Otherwise, it will be removed.
var regex = /\s\s+/gi;
input.value = input.value.replace(regex, "");
And if you need to remove all whitespaces, you can try
input.value.replace(/\s/g,'')
Just add a following check condition before invoking service.
input.trim() !=== ""
It's possible to pretty easily prevent only whitespace, use .charAt() to check if the first character is whitespace.
if the entire string is whitespace, then your first character is definitely whitespace.
Example:
if (input.value.charAt(0) == " ") {
//Do your things
}
As far as checking whether or not two immediately adjacent spaces are present, you can do that with regEx relatively easily, using an expression like [ ]{2,}.
In all seriousness, you're probably better off using a well-known, predefined form-validation library for the time being.
To avoid only white spaces given as input
Just add the following check condition
If ( input.trim() == "" ){
Expression
}
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'm pulling a string back from the database via jQuery, into a textarea, then upon user approval, grabbing that value and placing it in a text input.
Right now, my code looks roughly like this (some omitted of course):
var string = $('#textarea').val(); // Contains 145,095 char string
console.log(string.length); // logs 145,095 characters
// Clear Input and add approved string
$('#input').val('').val(string); // Contains 14,023 char string
Wondering where those ~131,000 characters are going? Based on some initial research, my understanding is that Chrome (in this case) should support millions of characters in a text input, so is this a jQuery limitation? I haven't found anything to support that hunch. Suggested work arounds?
You don't need to clear the input and then add the new value in, the JS can be streamlined to this:
$('#input').val(string); // Contains 14,023 char string
To be sure the value is being truncated, can you try and do a truthy match like so:
if (string === $('#input').val()) {
console.log('the values match');
}
If it does return true then it is just a visual thing, the content of the input box is intact :-) If not, then I would suggest adding a maxlength attribute to the input.
Hope this helps!
probably it is jQuery limitation
try to put Your text by parts or
try to use clear js : document.getElementById('input').value = string;
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.
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();