Javascript validation to allow maximum of 3 commas - javascript

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.

Related

Number only html input reading as null to my javascript when 'e' is part of input

I have a website built on cherrypy which a user can submit some information via a form on one of the pages and then via javascript has some validation that the required fields are filled in. I was originally attempting to verify some integer only fields were indeed integers with something similar to this within my submit javascript before I passed it onto a python function to handle my db and other submissions.
$("#btnSubmit").click(function(){
$("#dlgmessage").html("Processing...");
$("#dialog-message").dialog("open");
var assigned_port = ($("#txtAssignedPort").val())
if(
Number.isInteger(assigned_port) === false
){
$("dlgmessage").html("Assigned Port is an Integer only field")
$("dialog-message").dialog("open");
document.getElementById('txtAssignedPort').style.borderColor = "red";
document.getElementById('txtAssignedPort_label').style.color = "red";
return;
}
<--snip-->
};
That was not working for me though as no matter my input it was always false even if all I entered was numbers.
So, I moved onto instead adding some additional pieces to my html files which define the form. Previously they would all look similar to:
<label id="txtAssignedPort_label" >Assigned Port (*)</label>
<input class="form-control" placeholder="Assigned Port (numbers only)" id="txtAssignedPort" value="${assigned_port}" />
I then added some additional attributes to the input element like so:
<label id="txtAssignedPort_label" >Assigned Port (*)</label>
<input class="form-control" type="number" step="1" min="0" max="65535" placeholder="Assigned Port (numbers only)" id="txtAssignedPort" value="${assigned_port}" maxlength="38" />
This then restricted the user from even typing any non number value. But, as explained in this stackoverflow post, Why does the html input with type "number" allow the letter 'e' to be entered in the field?, the number fields will accept 'e' as a value since it can accept floating point numbers.
Doesn't seem like a huge issue that it supports 'e' but then the issue arrives when I attempt to submit something with an e in the input. I added a simple line to my javascript console.log("ASSIGNED PORT = " + ($("#txtAssignedPort").val())); in order to view what the javascript was viewing the input as. This results in a console log of ASSIGNED PORT = 12345 when I do only numbers but as soon as I use an 'e' it instead shows ASSIGNED PORT = with no value defined for my input ($("#txtAssignedPort").val()))
While I don't expect users to ever really try and submit one with an e, I still want to cover my bases to make my inputs as clean as possible.
Why is it that my javascript views that input field as null once an 'e' character is included?
Is there a better way I should be trying to accomplish this, like with the javascript I had at first that was not working properly at the time?

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.

JavaScript Max Length Validation with Overtype/Insert Key

I am trying to edit some existing JavaScript validation code.
Using the onkeydown event, the code checks that the value in a textbox does not go past a maximum length. I cannot use <input maxlength="value" /> as there may be some formatting characters in the string that I can safely exclude from the maximum length.
The code works fine apart from when the user has pressed the insert key to turn overtype on and they have reached the maximum length. When this occurs if they place the cursor before a character and try to overwrite it the validation thinks that this will go over the limit and doesn't realise that a character will actually be replaced.
This answer states that I cannot detect if overtype is on, but doesn't provide any references. So assuming that I cannot detect overtype, is there anyway in the onkeydown event to detect if a character is going to be replaced.
I am happy with an IE only solution.
Update: onblur is not appropriate as this will let them go many characters over the limit before warning them of the maximum length. I would like to prevent them from going over the limit.
Your handler should look at the entire value and check the length. If the length is legal, return. If not, you can update the value with a substring. You may have to use caret position to determine exactly how to manipulate the string which can be tricky as it's slightly different in IE and other browsers.
This is different from what you have now which is probably preventing keypress when max length is reached. Don't prevent keypress, just trim the resulting string.
I don't think your problem is with the onblur validation, but an event you calling on key press by the sounds of it (eg preventing the user to key any more once they reach the limit) or I have misunderstood.
IF your validation is indeed onblur, you shouldn't have to worry about things like insert/overwrite being enabled, you are only interested in what the value of the input element is once the user has completed their input.
IF you are trying to stop the user if they reach this limit as they type, I would write a function to compute the actual length you are testing. For eg,
function validateMyInput() {
var myInputField = document.getElementById('myInput');
var removeAllExcludedCharsResult = myInputField.value.replace('&','');//exclude &
var totalLength = removeAllExcludedCharsResult.length;
if(totalLength < 500) { //limit of this test is 500
return true;
}
else {
return false;
}
}
Obviously change this function to what you need and maybe make it more generic by passing in the element of the input, max length and array of excluded chars to make it reusable.
UPDATE
I have tested this problem is Chrome and the insert key seems to be ignored. IE on the other hand does overkey. However, it seems page specific, for eg, if i have enabled insert on Page A, it doesn't seem to affect Page B. I found this page which seems to be able to grab the keycode event even when insert has been pressed. It might be due to the following code?
if(window.event) {
event = window.event; //where event is the javascript key event.
}
Either way, the link above seems to have accounted for the problem, hopefully it will have the answer if the above is not correct.
Hope I haven't misunderstood what the problem was and this helped.

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