Text Input Character Limits - javascript

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;

Related

Escaping string using JavaScript before populating form input

I have this code where I grab an attribute value and load it into a form, the headline line can look something like:
Welcome to America's best valued whatever
But when using this escape function, the string is cut off at the apostrophe,
var headline = escape($(this).attr("data-headline"));
//populate the textbox
$(e.currentTarget).find('input[name="headline"]').val(headline);
I've also tried using the solutions here: HtmlSpecialChars equivalent in Javascript? with no luck.
How can I populate my input and keep apostrophe's/quotes?
Just use
$(this).find('input[name="headline"]').val(this.dataset.headline);
No need for any escaping.
However, notice that escape does not cut off apostrophes, it replaces them with %27. If your current code does not work with apostrophes in the headline, make sure that the markup containing the data-headline attribute is properly escaped by whatever tool is creating it.
var headline = $(this).attr("data-headline").replace(/'/g, '%27');
//populate the textbox
$(e.currentTarget).find('input[name="headline"]').val(unescape(headline));
If browser compatibility is important, dataset is only available IE11+ https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset#Browser_compatibility

Jquery allow spaces in alpha numeric validation

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.

How to handle possibly HTML encoded values in javascript

I have a situation where I'm not sure if the input I get is HTML encoded or not. How do I handle this? I also have jQuery available.
function someFunction(userInput){
$someJqueryElement.text(userInput);
}
// userInput "<script>" returns "<script>", which is fine
// userInput "<script>" returns &lt;script&gt;", which is bad
I could avoid escaping ampersands (&), but what are the risks in that? Any help is very much appreciated!
Important note: This user input is not in my control. It returns from a external service, and it is possible for someone to tamper with it and avoid the html escaping provided by that service itself.
You really need to make sure you avoid these situations as it introduces really difficult conditions to predict.
Try adding an additional variable input to the function.
function someFunction(userInput, isEncoded){
//Add some conditional logic based on isEncoded
$someJqueryElement.text(userInput);
}
If you look at products like fckEditor, you can choose to edit source or use the rich text editor. This prevents the need for automatic encoding detection.
If you are still insistent on automatically detecting html encoding characters, I would recommend using index of to verify that certain key phrases exist.
str.indexOf('<') !== -1
This example above will detect the < character.
~~~New text added after edit below this line.~~~
Finally, I would suggest looking at this answer. They suggest using the decode function and detecting lengths.
var string = "Your encoded & decoded string here"
function decode(str){
return decodeURIComponent(str).replace(/</g,'<').replace(/>/g,'>');
}
if(string.length == decode(string).length){
// The string does not contain any encoded html.
}else{
// The string contains encoded html.
}
Again, this still has the problem of a user faking out the process by entering those specially encoded characters, but that is what html encoding is. So it would be proper to assume html encoding as soon as one of these character sequences comes up.
You must always correctly encode untrusted input before concatenating it into a structured language like HTML.
Otherwise, you'll enable injection attacks like XSS.
If the input is supposed to contain HTML formatting, you should use a sanitizer library to strip all potentially unsafe tags & attributes.
You can also use the regex /<|>|&(?![a-z]+;) to check whether a string has any non-encoded characters; however, you cannot distinguish a string that has been encoded from an unencoded string that talks about encoding.

JavaScript replace() one html entity with another

I want to get some textarea text and replace all bullet point html entities • with ·.
The usual approach str.replace(/•/g,"·"); doesn't work.
Any advice would be appreciated.
When you're getting the text value back from the textarea, it has already been converted to its actual character. To do a string replacement on that string, either
convert all characters to their html entity counterparts, then proceed with what you're doing or
use the character in the regex directly.
Here's an example of the second approach.
var newText = oldText.replace(/•/g, "");
You can fiddle with an example here.
If you want to go with the first approach, see this question and its answers for ways to convert characters in a piece of text to their corresponding html entities.
If you want to do this without jQuery:
var myTextarea = document.getElementById('id_of_your_textarea');
myTextarea.value = myTextarea.value.replace(/•/g, '·');
jQuery:
$("#myTextarea").val( $("#myTextarea").val().replace(/•/g, '·') );
.val() will get the value from an input element, .val('str') will set a value.

How to ensure only valid numeric characters are entered into a textbox?

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();

Categories