jQuery validation plugin - partial validation depending on trigger - javascript

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

Related

Check Starting Form Values For JavaScript Validation

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.

jQuery validation, NOT the normal plugin

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).

Individual Input Validation on Blur

I'm trying to use HTML5 to validate a number input. I am using jQuery to create the element. How can I have the browser display the error message onBlur without having to click the submit button?
jQuery(document.createElement('input')).attr({"type":"number","min":"0","max":"60","step":"1","value":"5"});
Set up a .blur() handler. See here.
jQuery(document.createElement('input')).attr({"type":"number","min":"0","max":"60","step":"1","value":"5"}).blur(function(){
var val = parseInt(jQuery(this).val(),10);
if(val < parseInt(jQuery(this).attr('min'), 10))
jQuery(this).val(parseInt(jQuery(this).attr('min'), 10)); // Set value to min
if(val > parseInt(jQuery(this).attr('max'), 10)){
jQuery(this).val(parseInt(jQuery(this).attr('min'), 10)); // Set value to max
});
Something along those lines
Actually, you can't invoke the native validation ui through an API. Due to the fact, that the the validation ui automatically also focuses the element, this would not be a good usability (user can't leave field invalid and decide to do something else on the page).
If you want to do this: you have to implement the validation yourslf using the validity property and the validationMessage property. The code could look like this:
$('input[type="number"]').blur(function(){
//if field is validation candidate and is invalid alert the validationmessage
if( $.prop( this, 'willValidate' ) && !$.prop( this, 'validity').valid){
alert( $.prop( this, 'validationMessage' );
}
});
Of course using an alert, is a little bit stupid, but makes the code clean. If you want to use webshims lib, there is a showError helper. I have put up a demo here
About the helper method $.webshims.validityAlert.showFor:
showFor requires a dom element jQuery object or selector as first argument.
the validationmessage as optional second
and the last is a boolean, which will show the message without focusing the field.

Capture *all* display-characters in JavaScript?

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.

client-side text-box character limit validation using jQuery?

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" />

Categories

Resources