Restricting text box inputs to a given regexp using jQuery - javascript

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

Related

Javascript Regex - Match string shorter than expression?

let productIdPattern = /[0-9]{3}[A-Z]{3}[0-9]{3}/
let userInput = '123A'
if (userInput.match(productIdPattern)) {
alert("'123A' is ok, go ahead typing!")
}
Given is the above JavaScript pseudo code.
A User is typing a Product-ID. For every keystroke I want to check if the input will match the Product-ID pattern. If not, the keystroke will be ignored. So the input must follow the pattern.
For example:
Current input is "123", User presses "4" which is not valid and will be ignored.
Current input is "123", User presses "X" which is valid and will be appended to the input.
Is there a way to achieve this without making many different or complex patterns for each input length? I need a way to tell the "String.match()" function to ignore the rest of the pattern, if the string is shorter than the pattern.
We can create an input filter that only allows entering the desired pattern; everything else is immediately dropped. This is achieved using an in-place replacement pattern:
<input type="text" formControlName="productIdInputC"
onkeyup="this.value = this.value.replace(/^([0-9]{3}[A-Z]{3}[0-9]{1,3}|[0-9]{3}[A-Z]{1,3}|[0-9]{1,3})?.*$/, '$1')">
Though, you should still have server-side validation.
Try this pattern instead:
/^(?:\d{1,3}|\d{3}[A-Z]{1,3}|\d{3}[A-Z]{3}\d{1,3})$/
You can see a visualization of how this works here.

Cannot remove commas from input type number value

I'm trying to remove the commas from an input value using JS / jQuery.
The input type is number and I'm running the sanitisation process on key up.
The below code works fine when the input type is text, but not when the input type is number.
I'm using the input type number as a currency input, hence why I'm attempting to remove commas incase someone inputs $1,000 for example.
And I'd like to use input type number as this will mainly be used on mobile devices.
Does anyone know why that might be please?
-
http://codepen.io/anon/pen/YXvxxK
$('.form input').on('keyup', function() {
field1 = $('#field1').val();
var newField1 = parseFloat(field1.replace(/,/g, ''));
console.log(newField1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form class="form">
<input type="number" id="field1" />
</form>
The problem here isn't that you can't remove the commas, it's that commas aren't valid* within input elements whose type is number.
If we enter "1,234" into the field within your code snippet and hit Return, we're greeted with the following validation error:
This happens because the value "1,234" is deemed invalid. As this is invalid, the element's value will return as an empty string instead of the string value "1,234".
parseFloat("".replace(/,/g, '')) returns NaN.
A quick fix to this is to stop using the number input type and use text instead. However that may not be what you desire. Another way would be to detect whether the value is empty ("") and present the user with a validation failure message.
* It's important to note that this is implementation-specific. The HTML5 specification states that browser vendors are "encouraged to consider what would best serve their users' needs". Treating a comma here as invalid is part of that consideration.

jquery select2 plugin regex for allowed characters?

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');
// ...
});

Input field to only accept a specific number

I have created a form and now I want to add an input field inside it which would only accept a specific number i.e. the digit '4'. This is more like a spam check where the user is asked that 'What is the answer of 1+3?' and then he/she would've to enter the digit '4', in the input field, in order for the form to get processed. This could also work in a manner that if any other number is entered inside the input field and the form is submitted, a pop up window is fired explaining the error.
I have created a jsfiddle which only accepts the digit 4 but sadly it is allow accepting 'full stops'.
HTML:
<input id="humancheck" type="text" maxlength="1" name="humancheck" required />
Javascript:
jQuery('#humancheck').keyup(function () {
this.value = this.value.replace(/[^4-4\.]/g,'');
});
Your regex should only be replacing [^4] (any character which is not 4). I'm not sure why you have also included -4 (range) and \. ('.' character).
Just to note, securing on keyup doesn't help much. Anyone can fire up webkit inspector and place a 3 in there manually. If this is just a fun experiment, though, that's cool too :)
I know this post is a bit moldy, so I thought I might bring it a bit more current.
First, you should not use the 'keyup' for the event trigger, as it is to processor intensive. Imagine if you were wanting to match a number with more than one digit, and you can see how the 'keyup' becomes problematic.
Using the 'blur' event is a better trigger, as it checks the number value after the user has finished entering a number into the form field.
If I am understanding the OP, then why use a regex at all for a simple
match? Instead, this is one way I would write your function (for jQuery 1.11.0+). It also makes an additional check to assure the entry is indeed a number as well.
$('#humancheck').blur( function(){
if (isNaN(this.value)) alert('Not a Number');
if (this.value != 4) alert('Incorrect Number');
});

validation on input box

I want to create a Input Box for entering the private entering details of a person, On which first character has to be A or E and rest can be alphanumeric and no special character are allowed. I need to do validation for the same that no one enter any special character and First character has to be A or E (all has to be check on the client side)
Can any one guide me how to proceed
Look in to regex with JavaScript, along with the keydown event. You can attach a function to the keydown event, and inside this function check the input box(es) match and then proceed as you wish.
Something like this: (not tested)
<script>
function checkInput() {
var inputToCheck = document.getElementById('my_input');
if (!inputToCheck.value.match(/[AE]\w+/)) {
// do something here, like alert them or remove special characters with .replace
}
}
</script>
<input id="my_input" onkeydown="checkInput();" />
If this is the only field to validate I would write my own with js & regexp as Leonard Challis wrote (but on the keyup event).
If there will be a lot of fields and perhaps multiple forms on the site, I would consider a framework. This is pretty good: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
If you would be using that one you could write a custom function for your special needs. http://docs.jquery.com/Plugins/Validation/Validator/addMethod#namemethodmessage
This sounds like a homework assignment (since starting with specifically “E” or “A” sounds very artificial), so I’d suggest first deciding on the interpretation of the task. Should “E” and “A” be interpreted case-insensitively? What exactly does “alphanumeric” mean? For example, is “Σ” or “Я” or “١” alphanumeric? If the purpose is to do the checks client-side, should you try to make the page completely non-functional when JavaScript is disabled, or should you just do the checks client-side as far as possible? (In the latter case, consider using the pattern attribute in HTML. On some modern browsers, it causes the check to be performed even when JavaScript is disabled.)

Categories

Resources