Mask Text Input to Validate MM/YY jquery-mask-plugin - javascript

Using jquery-mask-plugin I want to mask an input to only accept reasonable MM/YY
$('#expDate').mask("99/99"); works but it allows for 55/66 which is not an acceptable month.
How can I make it so the first part of the mask is <= 12

You cannot do this with just the jquery-mask plugin. As you noted, it only masks out certain TYPES of inputs, such as numbers (in general), letters, symbols, etc. It does not perform data validation (which is what you're asking for.
You can write a simple jQuery function that runs onblur, etc that rejects invalid combinations:
$('#expDate').blur(function() {
let val = $(this).val();
if (val.indexOf('/') > 0)
{
let first = val.split('/')[0];
if (first > 12) $(this).val('');
}
});
Alternatively, you can use the great jQuery Validate plugin:
https://jqueryvalidation.org/
To be clear, you want data validation beyond just basic input masking.

Related

Currency input with Twitter Bootstrap (using jQuery)

I'm using Twitter Bootstrap (v3) and I want to make a money input, where I can enter an amount of money with a fixed currency (currently €).
The input type needs to be type="number" because of how I want the input to look on mobile devices (not a big QWERTY keyboard, just numbers), but I do want to allow multiple patterns.
I think the way to go is with the .on("input", callback) method, but I'm not sure how to accomplish this.
I have tried the following:
$(document).ready(function() {
$("#amount").on("input", function() {
// allow numbers, a comma or a dot
$(this).val($(this).val().replace(/[^0-9,\.]+/, ''));
});
});
(for the HTML and CSS, see the jsfiddle link)
But obviously that doesn't work, otherwise I wouldn't be posting here. Whenever you try to type something invalid, the whole string disappears.
http://jsfiddle.net/bjcayhzb/1/
Explanation rather than (or alongside) a working example highly is appreciated.
It is the type of input field 'number' that comes in the way. It has its own keyup/input handler attached (modern browsers deal with it via JS code too) and seems to break things.
If you use
<input type="text" required="" placeholder="42,00" class="form-control" id="amount" />
then this works:
$(document).ready(function() {
$("#amount").on("input", function() {
// allow numbers, a comma or a dot
var v= $(this).val(), vc = v.replace(/[^0-9,\.]/, '');
if (v !== vc)
$(this).val(vc);
});
});
The only drawback of this approach is that if you try to put bad character in the middle of the string, cursor jumps to the end. And, of course, you can type multiple dots and commas.
Better approach would be to keep last good value stored in data and test the whole string and replace if new character invalidates match for the whole string.
Update
When input type="number" value contains non-number, jQuery val() returns empty string. This is why your code is not working. If "number" is a must (e.g. for numeric mobile keyboard), an approach would be to keep last known correct val() and put it back into control.

Validation function for multiple inputs

I have a form with 2 number inputs and I am trying to validate it using the jQuery Validation plugin. I want to allow the form to be submitted only if the sum of the values is less than or equal to 10. For example, I want to allow 3 and 6, but not 7 and 8. How can I do this?
I was able to come up with something that works but I think it is inelegant and fragile to arbitrarily apply the rule to one input and use an attribute on that input to refer to the other input. I looked in the documentation for the plugin and I don't see any way of defining a validator that is meant to be used on more than one input. Can anyone think of a simpler way?
As far as the jquery validation plugin. No. A simpler way. Yes write your own in plain javascript.
function mySubmitfuntcion()
{
var myvar1 = document.GetElementById("1").value;
var myvar2 = document.GetElementById("2").value;
if(myvar1 + myvar2 <= 10) {
return true;
}
else {
alert("Please enter valid values");
return false;
} // end if
} // end function
returning false stops the mySubmitfunction() from completing.
In my experience writing custom validation scripts works better because you have more control. Remember to add the validation function to a button or the forms onsubmit event.

Javascript validation to allow maximum of 3 commas

I want a Javascript validation that allows maximum of 3 commas in a text field user to enter a number or text in format
123,456,789,0000
meaning 3 Commas(,) are allowed, there could be any number of digits/letters between commas. User may choose to enter only 2 Commas i.e. 3 values but max number of Commas that would be allowed are 3
for eg
a,bb,ddddd,eeeee (4 tags)
a,cc,bbbbb (3 tags)
What I am trying to achieve is user is allowed to enter only 4 comma separated tags thus making sure user cannot flood the article with 100's of tags
var txt = '123,456,789,0000';
if( /^([^,]*,){0,3}[^,]*$/.test( txt ) ){
// good
}else{
// bad
}
change the * to a + if you want to ensure that there aren't two commas in a row, e.g.: 12,,345
If you have control on server side, I suggest doing the validation there.
Because If you try to do the validation on the client using java script, it can be circumvented by either turning off java Script all together, or using Firefox's FireBug extension by manipulating or manually executing a request, bypassing your java script validation altogether.
But if you really still want to do some kind of validation in javascript, you can do something like the following:
Given this input field <input id="txtInput" type="text" />
You could bind a keyup event (pay attention to people attempting to paste from the clipboard, keyup will not catch it if they do it via context menu)
$('#txtInput').keyup(function(){
//This splits up the string value of the text box into an array
//wherever a coma appears
var tags = $(this).val().split(',');
//These would be your tags, without the coma, count them to find out how many
//the user tried to enter.
if (tags.length > 4)
alert('there is more than 4 tags');
});
Of course this is only an example, but you could adapt the idea to your needs. You don't have to bind this to the keyup event, you could bind this to a click event on the submit button or something, it all depends on your needs.

Javascript events

I am completely confused here. So I am looking for a solution for the following problem:
I want to trigger some function(for now an alert box) using jQuery on an input field. Conditions are:
Input field always maintains the focus.
Input is fed from a USB device, which acts just like a keyboard input. So for 10 characters, there will be 10 keydown and keyup events.
Once input is filled with 10 characters, respective alert box should pop out.
Now the problem I am facing, how do I find out that input fed in is not equal to 10 characters, so throw an error alert box.(lets say just 5 chars came in input, how do I figure out the final count is 5, because there will be 5 keyup events)
You could show a message underneath/beside the input box instead of popping an alert box.
E.g. on every keyup event, check the string length, and if it's not 10, show that message.
If you really, really have to resort to alert box, you could do a timeout check, e.g. only perform the validation after 1000ms of key event inactivity. This could get very annoying on the user though.
You really have two problems here. One is just understanding the jQuery syntax (see the second part to my answer), and the other is - what is the best way to understand WHEN to throw up an error box.
To answer the second question first, my recommendation would be to not use an alert box to warn the user as they tend to be modal and really interrupt the flow of input. Secondly, as you said - how do you know when the person has stopped "typing." Unless you use some sort of timing mechanism (which is more trouble than it's worth), you don't. My suggestion would be to utilize a "div" within your HTML that shows there is an error UNTIL you reach 10 characters. Once that happens, you can hide the div. (And, of course, the div can be styled to look pretty in the meantime.)
So...how to do this...
Let's assuming your input field has an id of "myField." If you are using jQuery (which is in your tags), you would do something like this.
$(function() {
var keypresses = 0;
$('#myField').keyUp(function () {
keypresses++;
if(keypresses == 10) {
$('#error').hide(); // This is your div error with some error text in it.
// Do other stuff.
} else {
// Display an error.
}
});
Alternatively, if you don't want to use the keypresses variable, you can also use..
if($(this).val().length == 10) { }
The real issue is the fact that you are measuring in key press events, because not all key presses (even when the field has focus) will insert a character into field (for example returnesc). Therefore, you will need to measure the string length in order to validate the code before you start executing functions.
In actuality you don't even need jQuery to accomplish what you need, just bind the function call to a key press event, and only execute the function call if yourstring.length = 10
yourInput.onKeyPress(yourString.length = 10 && yourFunction());
Try -
$('#idofinputfield').keyUp(function () {
var length = $('#idofinputfield').val().length;
if(length <= 10){
alert("less than 10");
}else{
alert("greaterthan 10");
}
});

Limit an html form input to a certain float range

Is there a way to limit a form input field to be between certain number range, say (0,100)
I'm filtering the input in the onkeydown event, to accept only numbers, the problem
is I want to reject a number if that number would make the input to go out of range
So I need a way to see if the current value of the input plus the key the user is pressing
will sum up between the range.
I tried using:
if((parseFloat(this.value) + parseFloat(String.fromCharCode(e.keyCode)) > 100){
return false;
}
the thing is e.keyCode can return different codes for the same number, right now is returning 57 for the
number 9, but 105 if i press the number on the numpad.
Is there a way to accomplish this?
Personally, I would just check it when the field loses focus (or when the form is submitted). Popping up errors as the user is typing (or preventing their keystrokes from registering in the field) is usually just going to annoy them.
And of course you probably knew this already, but make sure you check the value on the server side after the form is submitted as well. Never rely on javascript validation!
Trying to anticipate what the resulting value is going to be is harder than you think. Remember the user might be pressing backspace, or the cursor might not be at the end of the field, or the user might have part of the value selected, to be replaced on next keypress, and so on. It's also possible to manipulate the text field through mouse operations you won't get any say in.
The traditional approach is to put your validation on the ‘keyup’ event instead of ‘keypress’. Then you get the full, post-change value of the field. You don't get the chance to deny the keypress, but you can reset the field to the last-known-good value instead.
But either way it's best not to try to constrain input too tightly, because this can make it terribly difficult to type. For example, “12.” is an invalid number you might want to deny... but if you did, it would become very difficult to type “12.3”! Better to allow any input, but signal when the current input is out of bounds, by some mechanism (eg. turning the text red is common).
Adding the current value plus the float value of the character typed is not what you want. Think about if the current value is 99.0 and the user types a "5", the actual value is 99.05 but your expression would evaluate to 104.0. You need to append the key character to the current value before parsing anything into a float.
As for the key code, here is a reference to the javascript key codes. Using that you could write your own function like this:
function fromKeyCode(code) {
var asciiCode = code;
if (code > 95 && code < 106) {
asciiCode -= 48;
}
return String.fromCharCode(asciiCode);
}
var total = new Number(20.00);
alert(total.toFixed(2));
That will allow you to set a fixed width on the precision of 2 decimal places. In this case I am making sure with a js required field check that money only has 2 spots after the 2.
I'm not sure if I understand your question fully, but check the Number() methods, there has to be something there to help you.
You can catch the input on keyup, after the value contains the new input.
Then just look at the value-
inputelement.onkeyup= function(e){
e= window.event? event.srcElement: e.target;
var val= parseFloat(e.value) || 0;
e.value= Math.max(0, Math.min(100, val));
}

Categories