Is there anyway to define a set of "allowed" characters for user input? For e.g. alphanumeric input only. Can't seem to find it within the official documentation
You can accomplish this using the createSearchChoice option, which allows you to define a custom function to create tags from user input. To not allow tags containing other than alphanumeric characters, the select2 should be initialized as:
$("#mySelect").select2({
createSearchChoice: function(term) {
if(term.match(/^[a-zA-Z0-9]+$/g))
return { id: term, text: term };
},
formatNoMatches: "Enter valid format text"})
If the user is typing text that contains non-alphanumeric characters, the dropdown below the select2 will show no matches. It's not necessary to specify a custom formatNoMatches but it is more helpful for the user than the default "No matches found" to figure out why their input isn't being accepted.
Update:
As of select2 version ~ 4.0 this function is now called createTag
I didn't find anything about put a mask/regex on the input where you type.
But you can do it on the 'open' event provided by select2.
Something like this:
$('select of the select2 input or select').on('select2-open',function(e){
// apply your mask on this element -> $('.select2-input')
});
Hope it helps you.
Bye
Today I was finding a way to apply a custom mask on the input that appear in the dropdown (select2 v3), and I found this topic.
After some research on official doc I saw the method select2("container"), and looking the source code I found select2("dropdown") (not present on doc).
So, my final code is (for contribution purpose):
$('my-select2').on('select2-open',function(e){
var input = $(this).select2("dropdown").find('.select2-input');
// ...
});
Related
Here is the page
If you select one of the 3 modems, it will open up the form below.
On the Billing > Address Line 1 field (left col), I'm trying to check for a PO Box entry and display a hidden message above the field. We're trying to discourage PO Box, but it should still allow submit, so I'm handling this separately from the jq val plugin on the form.
It's just not working, no matter what I try. The bind on the input is working, since it's logging properly, must be an issue with the regex, but I can't pinpoint it.
Here is the current js
var pobox = new RegExp('[PO.]*\\s?B(ox)?.*\\d+', 'i');
$("#bill_address1").bind("change paste keyup", function(){
if ($(this).val().match(pobox)) {
$('#pobox-warning').fadeIn(50);
console.log('box');
}
else {
$('#pobox-warning').fadeOut(50);
console.log('no box');
}
});
Any help would be appreciated - thanks!
It seems to me that a simple regex pattern like
/PO *Box/gi
would work best. Ignore case. Match the letters PO and any number of spaces followed by the word Box.
Edit:
Or to match the entire PO Box line with or without periods:
/P\.?O\.? *Box *\d*/gi
The initial part of your regular expression matches either a single "P", an "O", or a ".". You probably want something more like:
var pobox = /(P\.?O\.?)?\s*B(ox)?.*\d+/i;
It's much easier to use the native regular expression syntax in JavaScript when possible, as it appears to be in this case.
got it working with
var pattern = /^[P|p](OST|ost).*\s*[O|o|0](ffice|FFICE).*\s*[B|b][O|o|0][X|x]\s*(\d.)*/gi;
appreciate everyone's input
I have a problem with the Chosen jQuery plugin. When I try to search for a string which has space in it I get no results even if it does exist.
For example:
If I enter the string "and barbu" I don't get anything back. But when I write "antigua and barbu" I get the result.
What should I do to fix this space problem?
Answer here : Changing search behavior in jquery plugin Chosen
Just need to add
jQuery('select').chosen({search_contains:true}) ;
As mentionned on the options doc :
http://harvesthq.github.io/chosen/options.html
search_contains false By default, Chosen’s search matches starting at the beginning of a word. Setting this option to true allows matches starting from anywhere within a word. This is especially useful for options that include a lot of special characters or phrases in ()s and []s.
I'm trying to filter a jquery DataTables table with keyword/tags entered through a Select2 tagging interface using the regex filter so I can filter on OR instead of exact match.
I'm initializing the DataTables with the separator set to pipe | (regex OR) but it's still separating the tags with commas in the value attribute of the input.
jQuery('#programs-table').dataTable({
"sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"bPaginate": false,
"separator": "|"
});
jQuery("#program-filter-keyword").change( fnFilterGlobal );
Even if I manually change the search field it doesn't always filter with OR, mostly when using two word tags or tags with a comma like the 'protection, security...' - I think I can get around the 'separator' option not working as it should by using replace on the input value to turn commas to pipes although that's not ideal as some tags have commas and I also need to replace spaces and comma+spaces with their regex counterparts to make it work.
function fnFilterGlobal () {
jQuery('#programs-table').dataTable().fnFilter(
jQuery("#program-filter-keyword").val().replace(',','|'),
null,
true,
true
);
}
The way I see it, I have two options:
Does anyone know the proper way to set this up to use tags from select2 as an OR filter on datatables
I'm new with regex - is there a way to convert what Select2 is inputting as the input value for the tags into a proper regex OR search including the tags with spaces/commas?
Here is a CodePen (jsFiddle is down) of an example. http://codepen.io/tsdexter/pen/GcnxA
Thanks.
I've figured out a way to do this which is, so far, working in all use cases I've tested.
I'm basically bypassing the value that Select2 passes to the hidden input field since it messes up the commas due to the 'separator' option not actually changing the separator for tags-mode (it only works with multi-select inputs).
Here is the filtering function:
function fnFilterGlobal () {
var tags = [];
jQuery("#s2id_program-filter-keyword .select2-search-choice div").each(function() {
tags.push(jQuery(this).text());
});
jQuery('#programs-table').dataTable().fnFilter(
tags.join("|").replace(/ /g,"\\ "), null, true, false
);
}
I'm building an array of the selected tags by parsing the <ul> list that Select2 creates and extracting the tags values from the <div> content.
Then for the actual filter string I've joined the array items with the pipe symbol for the OR functionality and replaced all spaces with \ (escaped space).
Lastly, I set the 'smart filter' option to false - this is key, otherwise it will try to turn the filter string into a complicated regex which I've already made it one and the escaped spaces cause invalid regex errors.
I've updated the CodePen so you can see how to have multi tag OR filterable tables using Select2 and DataTables http://codepen.io/tsdexter/pen/GcnxA
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.
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