I have a textbox that must have a MIN number of characters as well as a MAX number of characters. What is the best way, using jQuery, to make sure that the input is within the range (while displaying status messages to the user) before allowing the user to submit the form?
Update: the code below works to some degree, however I am getting issues when deleting text. Since it is using 'keypress' to capture events in the textbox, the 'length' variable gets falsely incremented when hitting backspace for example. It seems like the issue is that the length of the text is retrieved before the fact i.e. a keypress will always result in a length of what was there before plus 1. What is the proper way around this?
Update: I think i solved the previous issue by using the keyup function instead of keypress
If this is the only client side validation in your app (always validate on the server too!) then it'd look something like this:
$("#your_textbox").keypress(function() {
var length = this.value.length;
if(length >= MIN && length <= MAX) {
$("#your_submit").removeAttr("disabled");
$("#your_validation_div").hide();
} else {
$("#your_submit").attr("disabled", "disabled");
$("#your_validation_div").show();
}
});
If you need a lot of validation in your application you might want to consider the validation plugin.
Setting the maxlength attribute:
<input type='text' maxlength="30" />
Related
I have an HTML form that I already validate using Javascript. However, I am only checking to make sure it has been filled out. I also need to check to be sure that the first eight characters of the form do not contain "FFFFFFFF" or "ffffffff". It will be a 40 character input into the form field. I am just not sure how to do this with Javascript.
If someone could point me in the right direction, I would really appreciate it.
var txt = document.getElementById('id').value;
var first = txt.substring(0,8);
if(first=="FFFFFFFF"||first=="ffffffff"){
// validation error
else
//validation success
as simple as that. i can't be more specific since you haven't shared any of your code.
I've been looking at the jQuery Validation Plugin and it seems like overkill (my site's script requirements are ballooning), and also not quite what I want.
Let me define some terminology: an <input type="text"> field's status is VALID if it matches both RegEx 1 and RegEx 2, PARTIAL if it matches RegEx 1 but not RegEx 2, and INVALID if it doesn't match RegEx 1.
For example, RegEx 1 could be /^[A-Z_]*$/ and RegEx 2 could be /^[A-Z]+(_[A-Z]+)*$/.
The requirements are:
any key press which would lead to an INVALID status is ignored, without interfering with focus or the caret position, and without the value ever being seen to change,
otherwise the status is updated after every key press to be either VALID or PARTIAL, and
whenever an input's status changes, a callback is invoked.
Seems pretty straightforward. This is basically the QStringValidator model.
I have jQuery core but I'm new to it. How can I implement this? Thanks.
P.S. if the best solution lies outside of jQuery, IE support is not required.
if (this.value.match(this.getAttribute('data-regex1')) {
if (this.value.match(this.getAttribute('data-regex2')) {
do_whatever_for_full();
} else {
do_whatever_for_partial();
}
} else {
do_whatever_for_invalid();
}
Put your regexes into the element as custom attributes (data-regex1, data-regex2) then check the data as it changes (not sure how many events you want to check but you probably have to check with onkeydown ignoring enter and tab, or you could create a timer onfocus and just check every half second or so).
...with jquery/javascript? I want to check and make sure that a value has been entered and that it's a number.
First - Is it a best practice to do validation on the client-side, server-side, or both? Is this something that should be validated twice or is checking on the client-side enough?
Second - If client-side validation is the best way to go about this, how could I do this with javascript/jquery? I assume that for the button that's clicked, I would assign its onclientclick equal to a javascript function.
1) Validation should, at minumum be done on the server side. Both is even better.
2) If you wanted to do easy validation, you would simply attach to either a button click event, or better even, the form submit event.
$('form').submit(function()
{
// Do My Validation
// return false if invalid, true otherwise
});
You need to do both, and you should use jQuery Validate for the client-side.
Client side validation is purely for convenience of user and server, NOT for data sanitation. Consider the fact that you can open your dev tools and change the JS as you please on the fly - you could completely bypass client side validation. It is, however, good that it doesn't require you to load any more data and allows you to validate before navigating off.
Like the other answers say, using server-side and client-side together would be best. Client-side can always be passed by people knowing what they are doing. Even if someone just turns off Javascript all-together, client-side validation is worthless.
My recommendation is to set up everything on the server, then go back and fix it for the clients. Javascript and jQuery are the most common items used for validation. One of the things I use with Javascript is preventing any submit button until after everything checks out, for example:
document.getElementById("submitbutton").innerHTML = '<input type="submit" value="Log In" />';
Putting in that after everything checks out with the validation would place the input button in a div with the id of "submitbutton".
An example of some Javascript just to make sure there is input for a box would be this:
var textValue = document.getElementById("idOfTextBox").value;
if(textValue == null || textvalue == "")
{
document.getElementById("errordiv").innerHTML = "Please fill out a value for the text box";
}
If this is set for onKeyUp or onBlur for each text box, it can be pretty useful in making sure every box has its input.
There are few client side Validations here
First - Is it a best practice to do validation on the client-side,
server-side, or both? Is this something that should be validated twice
or is checking on the client-side enough?
Client Side - It is always good. provided that the javaScript is not blocked. Client side validation speed up the process. Reduces the execution time.
Server Side - It's always bother-less. Just need to compromise with the performance.
Both Side - I can go for RegularExpressionValidator and Server side validation.
Second - If client-side validation is the best way to go about this,
how could I do this with javascript/jquery? I assume that for the
button that's clicked, I would assign its onclientclick equal to a
javascript function.
In this Example I will explain how we can prevent the user to type non
alphabets in numeric textbox.
Mark Up
<asp:TextBox ID="FirstName" runat="server" AutoComplete="Off"
onKeyup="return AlphaNumeric(this);" onchange="return AlphaNumeric(this);"></asp:TextBox>
Sample JavaScript code
<script language="javascript" type="text/javascript">
function AlphaNumeric(controlID) {
document.getElementById(controlID.id).value =
NumericValidation(document.getElementById(controlID.id).value);
return true;
}
function NumericValidation(val) {
var Reg = new RegExp('[^a-zA-Z]+');
var Result = val.match(Reg);
if (Result) {
val = val.replace(Reg, '');
return val;
}
else
return val;
}
</script>
I am using the jQuery validation plugin and I would like to validate a floating point number and format it to a specified number of decimal places.
I am using
element.value = parseFloat(value).toFixed(param);
to format the floating point value if it is indeed a valid floating point value, I just only want to do this on blur, not on keyup as this yields odd results. I do however want to validate the input on keyup.
I guess what I am looking for is basically
if( validation was triggered by blur )
{
element.value = parseFloat(value).toFixed(param);
}
The jQuery validation plugin does not allow you to mix rules like that (I might be wrong, there may be an option to do that, but this problem is easy enough to solve without it anyway.)
First, for the keyup validation:
$('#float').keyup(function(){
if(!/[-+]?[0-9]*\.?[0-9]+/.test(this.value)){
// Do something about the error
}
});
You might want to rollback the edit or display an error message, whatever. Now, on blur
$('#float').blur(function(){
var input = this.value;
if(/[-+]?[0-9]*\.?[0-9]+/.test(input)){
this.value = parseFloat(input).toFixed(param);
}
});
There, simple.
NB: Regex from http://www.regular-expressions.info/floatingpoint.html
I was given an unusual request recently that I'm having the most difficult time addressing that involves capturing all display-characters when typed into a text box. The set up is as follows:
I have a text box that has a maxlength of 10 characters. When the user attempts to type more than 10 characters, I need to notify the user that they're typing beyond the character count limit.
The simplest solution would be to specify a maxlength of 11, test the length on every keyup, and truncate back down to 10 characters but this solution seems a bit kludgy. What I'd prefer to do is capture the character before keyup and, depending on whether or not it is a display-character, present the notification to the user and prevent the default action.
A white-list would be challenging since we handle a lot of international data.
I've played around with every combination of keydown, keypress, and keyup, reading event.keyCode, event.charCode, and event.which, but I can't find a single combination that works across all browsers. The best I could manage is the following that works properly in >=IE6, Chrome5, FF3.6, but fails in Opera:
NOTE: The following code utilizes jQuery.
$(function(){
$('#textbox').keypress(function(e){
var $this = $(this);
var key = ('undefined'==typeof e.which?e.keyCode:e.which);
if ($this.val().length==($this.attr('maxlength')||10)) {
switch(key){
case 13: //return
case 9: //tab
case 27: //escape
case 8: //backspace
case 0: //other non-alphanumeric
break;
default:
alert('no - '+e.charCode+' - '+e.which+' - '+e.keyCode);
return false;
};
}
});
});
I'll grant that what I'm doing is likely over-engineering the solution but now that I'm invested in it, I'd like to know of a solution.
The simplest solution would be to specify a maxlength of 11, test the length on every keyup, and truncate back down to 10 characters but this solution seems a bit kludgy.
It is also easily defeated by cut/paste, drag/drop, right-click-undo/redo, etc. There's no reliable way to get every potential bit of input short of polling.
Why not set maxlength to 10, to let the browser enforce the limit properly, and just show a warning if there is another attempted keypress? You don't need to prevent any default action because the browser is already taking care of the length, so the amount of key checking you have to do is lower.
<input id="x" maxlength="10"/>
<div id="x-warning" style="display: none;">can't type any more!</div>
<script type="text/javascript">
function LengthMonitor(element, warning) {
element.onkeypress= function(event) {
if (event===undefined) event= window.event;
var code= 'charCode' in event? event.charCode : 'which' in event? event.which : event.keyCode;
var full= element.value.length===element.maxLength;
var typed= !(code<32 || event.ctrlKey || event.altKey || event.metaKey);
warning.style.display= (full & typed)? 'block' : 'none';
};
element.onblur= function() {
warning.style.display= 'none';
};
}
LengthMonitor(document.getElementById('x'), document.getElementById('x-warning'));
</script>
Since you're using JQuery already, .validate() is terrific for forms. Just set a rule of maxlength for your field, and you're good to go. E.g.
$("form[name='myform']").validate({
rules: {
myfield: {required:true, maxlength:10}
}
});
I had a vaguely similar situation come up in a web-app I am working on where I needed to give feedback to the user, live, as they entered data into an input.
Honestly, the best solution I came up with was just to use a setTimeout to poll the input box periodically. I did a few tests to find a nice balance between responsiveness and efficiency (I think ~400ms).
It works great, and is much better than trying to kludge together event handlers for every scenario (key-down, on-change, etc etc).
It's not as elegant as I would like, but it works.
If you really want to do this, I would watch the input in real time, checking it's length. If it's over the limit, chop it and alert the user.
This would not be a replacement for other validation of course.
I would also consider that this may be unnecessary. I suppose it's nice, but most websites get by with a hard limit and validation-on-submission.
How about presenting a message to the user when they go over the limit, but not truncating their input? You can prevent submission using the onsubmit event and the user will never have the poor experience of a maxlength or a transient input. You can highlight the box in red or display an icon as well to really drive the point home.
However, this is all client-side, so if you really need to validate the input, that must be built into the submission target's server-side logic (in the case of a form).
Alternatively, if this is happening in real-time, link the logic to a variable that is set by the key-up event. If the length limit is exceeded, present an error message, do not truncate, and do not update the private variable.