I have a text area which gets filled in various ways including paste, keyboard input, from an autocomplete etc.
Now I want to validate this text area and if contains any combination, including multiples of some characters and if so, set it to empty.
The characters I want to filter are: tabs, new lines, spaces, carriage returns, as well as some watermark text - basically any non-meaningful character.
Note that valid text might contain special characters such as ()!#%<>,;:/||{}[] and possibly a few more.
Valid values might contain new lines, spaces etc. but will also have other valid characters (the stuff above plus 0-9, a-z, A-Z etc.)
Currently, I have the following wrapped in a jquery .change event:
<textarea cols="70" rows="3" class="cssTextarea cptEntryArea formFocus"></textarea>
$('.cptEntryArea').live('change', function(e)
{
var myval = "";
myval = $(this).val().trim();
myval.replace(/\r\n|\r|\n|\u0085|\u000C|\u2028|\u2029|^\s*$|^\s+|\s+$/g, "");
if ((myval == watermarkText) || (myval.length == 0))
{
$(this).val("");
e.stopPropagation();
return false;
};
});
The idea is to simply blank it out if it has "non-visual" characters in it in any combination.
Any optimization or better method to get this done?
EDIT1: Looks like I can do some adjustment here as the jQuery trim is:
trim: function( text ) {
return (text || "").replace( /^\s+|\s+$/g, "" );
}
Sounds like a very strange thing to do. What is the watermarkText for? Would it not be a better idea to catch before the text is put into the textarea i.e. on keydown, return null if the ascii value < 33? Your event only fires when the item is changed/lost focus, not immediately when some text is entered.
You could try doing /mg for the regex multi-line.
As it ended up, I had to manage my keystrokes more efficiently as well as the event management of the end result. My solution is a quite complex interactive page where multiple methods are used to populate the value with configurable options of which group of methods and the acceptable values that are allowed, thus the complexity of the resolution.
various methods used to populate the textarea:
Free form (user entered)
Autocomplete - validated against and choosen from a user entered string to produce the select list.
Text MUST match the database exactly
Freeform text allowed, but the associated ID must be in the database
New user text allowed, but must be posted as a new value to the select list
programatic population (pull from database/other value and populate)
All of this makes the validation rules complex however the other answer is being accepted as it best helped resolve the issue.
Note that there are actually multiple keystrokes that get in play here with various actions based on the keystroke and the options in play for a particular user.
Thanks to everyone for the assistance.
Related
I am a newer front-end dev fresh out of college. This is my first time encountering an issue like this. I am working on a coworkers code so I don't want to change his code too much, simply fix an issue with his code without completely overhauling it.
We have 3 input style fields: input, phone, number
The input field is a free text field used for things like names.
The phone field is a number only field that formats number sequences into a 10 digit phone number with a (XXX)XXX-XXXX format in real time on the screen for the user.
The number field is used for things like ssn where only numbers are allowed. Non-numeric characters get rejected
All three of these fields extend a base format field. Inside this base format field, we have an onKeyUp(event: Event) function that calls a format function every time the user types a character. We do this to add things like the ( ) in the phone field as they type and remove non-numerical characters from the number fields as they type.
HERE IS THE ISSUE
By calling the format function on every keystroke our cursor is jumping to the end of the value in the input field after each keystroke. So if I have a pre-existing name in an input field: "John Smith" and I want to go back and edit that field to look something like "John Joe Smith" my cursor jumps to the end of the string after each keystroke.
My goal is to keep the formatting on keystroke so that phone numbers continue to be formatted and the number fields reject the non-numeric values in real time, but also I want to allow mid-value editing without kicking their cursor to the end of the value after each keystroke.
Is there a way to capture my cursor location before I call the format and then return my cursor location after the format? Or another solution that might be easily implemented?
You can get the caret location from the element that triggers the event and then insert the text at that location using substring. Here's a snippet from a project of mine where I had to handle inserting tab characters (\t):
case 9: // Insert tab key at caret location
e.preventDefault();
var caret = e.target.selectionStart;
e.target.value = e.target.value.substring(0, caret) + '\t' + e.target.value.substring(caret);
break;
How to validate or mask some special characters while giving input in JavaScript/ JQuery
Suppose in password use of _ and & is allowed, So all other special characters when I use as an input show validation message immediately or should not be typed (get masked)
Whell Validation and masking are two different things.
When you want to validate, you simply add onkeyup event
$('input').keyup(function(){
var inputText = $(this).val();
if ( !/[a-zA-Z0-9]+/.test(inputText) ){ // put your reg exp here, this will require only letters and numbers
console.log('Display error');
}else{
console.log('Hide error');
}
});
When you want to mask your characters, you need to create seocnd hidden input, next to your input and copy your input value. After you cope input value, you can replace spacial characters with some char and place it inside of your input.. This one is more complicated than first case.
Most ppl would advise to use validation.
Just remember not to do mutch operations here, if you are worried on performance, and you can accept validation on value change, I would advise onValueChange event instead.
Is it possible using Javascript (or any other language if not) to detect if a user types in the word URGENT (any case) or *URGENT* as the first word in a text field?
If so, could I get the form to pop up a message either on submit or when they type it asking them politely not to start their call with this? If they include the word anywhere else then this is fine, it's just at the start that we don't want it. Thank you.
With some little research you can know that the answer to your question is yes.
Your question has been asked and answered many times, therefore it will better for your learning expericence to do some research about it.
How? Kindly read:
developer.mozilla String/indexOf
Javascript indexOf case insensitive
//first step, catch the text that user has entered from an input with the id someTextField
var str1 =document.getElementById("someTextField").value;
//assign some values to search for, words listed here will trigger the alert.
var wordsToFind = ["urgent", "*urgent*"];
//for now, we will take the user's input, str1, and convert it to lower case, then try to check if the first word (indexOf)the words to find is 0. 0 means at the beginning of the text.
//find first word in array
if (str1.toLowerCase().indexOf(wordsToFind[0]) === 0
//find second word in array by adding OR ||
|| str1.toLowerCase().indexOf(wordsToFind[1]) === 0) {
//display a message to inform the user.
alert("Kindly you can not start a message with the word 'urgent'");
}
If you have many words, then you can put them all in the array and loop through it and try to see if the user's text contain any of the blacklisted words.
First, you will need to get the text from the textbox with something like
var s = document.getElementById('myTextBox').value;
Once you have that, there are a number of ways you could check to see if it starts with the word "URGENT". One example would be
var containsUrgent = s.substr(0, 6).toUpperCase() === 'URGENT';
Once you've done that, the simplest way to display the message on the screen would be
alert('The string in the textbox starts with URGENT');
This is not a best practice, but it should help you get started.
If you want to alert the message when the user types or submits the form, you can attach your code to the submit and keypress events.
I have a login form that users are constantly getting wrong. We are working on better informing the users but we would also like to hint them in the correct direction as they type in the input field.
All IDs are 10 characters and they start one of 4 different ways:
A00
B00
CTR
VST
I would like to hint users if they don't start with one of those 4 options, likely by triggering a hidden element to reveal itself that reminds them what a username looks like.
Most of the jQuery I can figure out, the only part I can't is the actual matching. I'm not really sure how to write the RegEx to make it work.
This will match a correct string
^((A00)|(B00)|(CTR)|(VST)).*$
In JavaScript
if (txt.search(/^((A00)|(B00)|(CTR)|(VST)).*$/) !== -1) {...}
Consider the following text box:
<input type="text" name="quantity" id="quantity_field" />
Using jQuery I want to restrict the set of valid inputs into quantity_field by the following regexp:
<script>
var quantityRegexp = "^(0|[1-9]+[0-9]*)$";
</script>
More specifically I want to make the browser discard any characters entered into quantity_field that would make the value of the text field not conform to the given regexp. (A corresponding check would of course also be made on the server-side.)
Examples:
If the user types "foo 234" only "234" would get entered in the text box.
If the user types "001230" only "1230" would get entered in the text box.
If the user types "foo1bar" only "1" would get entered in the text box.
Question: What is the simplest way to acheive this using jQuery?
Not an answer to your question (since I have no knowledge of jQuery), but the regex ^[1-9]*[0-9]*$ might not do as you expect or think. It matches empty strings but also a number like 000000. I expect that you don't want that since your first character class [1-9] explicitly ignores the zero. I think you should change the first * into a +: ^[1-9]+[0-9]*$. However, that regex will reject the (single) number 0. If you want to include that, you should do: ^(0|[1-9]+[0-9]*)$.
If you don't know how many characters the user is going to type in (and just want to restrict them to numbers), the jQuery Validation Plugin is your best bet.
$('form.to-validate').validate({
rules: {
quantity: { digits: true }
}
});
That will only allow the user to enter in digits. If you know how many characters the person is going to type, then I also recommend using the Masked Input plugin for jQuery, which will give the user a nice visual indication of what they need to type and also prevent them from entering in characters you do not want in the field.
If you're not after just digits and must check against a regular expression, this post has the method to add a custom validation method to the jQuery Validation Plugin which should get you what you want.
Hope that helps!
I advise you to let the user tpye whatever he wants, then do a validation on submit of the form. (Of course you must still check on the server-side as he could easily disable or alter the javascript validation code)
For validation look into the
jQuery Validation Pluging
Define a global variable "oldVal" (not described below), which contains the last known good value. Bind to the keydown action for the input field:
<script>
$("#quantity_field").keydown(function() {
var newVal = $("#quantity_field").val();
var quantityRegexp = /^(0|[1-9]+[0-9]*)$/;
// success
if (quantityRegexp.test(newVal)) {
oldVal = newVal;
// hide error
$("#quantity_field_error").hide();
}
// else failure
else {
$("#quantity_field").val(oldVal);
// display error message
$("#quantity_field_error").show();
}
});
</script>
This should get you started