validating input text field (max and min) based on checkbox condition - javascript

What I am trying to do is to apply some validation on an input text field based on a checkbox and whether it is checked or not.
Case 1: when check box is selected, user can only enter numbers from 0 to 100 (decimal included. So 34.35 is allowed)
Case 2: Normal numeric validation
However the behavior of my code in Case 1 is it only allow user to enter 1 nu,beric digit between 1 to 9.
Here is my code.
HTML markup
elements.stakeInput = $('<input placeholder="0.00" type="text" style="float:right" />');
elements.promoMoneyCheckbox = $('<input type="checkbox" />');
JS
elements.promoMoneyCheckbox.click(function() {
SingleDiv.prototype.validatePromoInputField(self);
});
validatePromoInputField : function(singleDiv) {
var self = this,
elements = singleDiv.getElements(),
promoMoneyCheckbox = elements.promoMoneyCheckbox;
if (promoMoneyCheckbox.is(':checked')) {
elements.stakeInput.attr("placeholder", "10.00");
elements.stakeInput.keypress(function(event) {
var num = parseInt(self.value, 10),
min = 0,
max = 100;
if (isNaN(num)) {
this.value = "";
return;
}
this.value = Math.max(num, min);
this.value = Math.min(num, max);
})
}
else {
elements.stakeInput.attr("placeholder", "00.00");
validateInputs(event, 'decimal')
}
}
function validateInputs(event, typeOfInput) {
event = event || window.event;
if (event.ctrlKey || event.altKey || event.metaKey) return;
var regex;
switch (typeOfInput) {
case 'decimal':
regex = /^[.0-9]$/;
break;
case 'minAndMax':
regex = // May be I could add a regex over here instead of the validating in validatePromoInputField fucntion
break;
default:
regex = /^.$/;
break;
}
var char = getKeypressChar(event);
if (char == null || regex.test(char)) return;
event.preventDefault ? event.preventDefault() : (event.returnValue = false);
}
Is there any simple way to achieve this?
I am not looking for HTML5 validation i.e (input type="number" min and max value).

Use jquery .change() event to detect changes of the input and parseInt to verify the input.
$("#in").change(function(e) {
var val = parseInt($(this).val());
if (!isNaN(val)) {
if (val >= 0 && val < 100) {
$("#out").html("good!");
return;
}
}
$("#out").html("bad!");
});
http://jsfiddle.net/VxM4h/1/
Remember that client side changes can be altered. Make sure to verify your input on the server side as well.

Related

How to PREVENT (Not Validate) Users from entering more than 4 Decimals in an HTML Field [duplicate]

I have got a task to prevent keypress two digits after a decimal number.
My jquery file is
$(function(){
$('#name').bind('paste', function(){
var self = this;
setTimeout(function() {
if(!/^[a-zA-Z]+$/.test($(self).val()))
$(self).val('');
}, 0);
});
$('#salary').bind('paste', function(){
var self = this;
setTimeout(function() {
if(!/^\d*(\.\d{1,2})+$/.test($(self).val()))
$(self).val('');
}, 0);
});
$('.decimal').keyup(function(){
var val = $(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9]./g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
$(this).val(val);
});
});
My html page is
<b>Name</b>
<input type="text" id="name" /><br/>
<b>Salary</b>
<input type="text" id="salary" class="decimal" />
here i want only write 2 digits after decimal,how can i do this?
You can see my code in http://jsfiddle.net/V6s4B/
You can handle the key event before keyup on keypress, if the input is not to our liking we can disable the event from occurring. Something like this:
Update
Unfortunately my original answer below fails on certain numbers that can't be represented accurately as a float. Here is another solution that checks the position of the '.' character against the length of the string with a handy helper function.
jsFiddle
$('.decimal').keypress(function (e) {
var character = String.fromCharCode(e.keyCode)
var newValue = this.value + character;
if (isNaN(newValue) || hasDecimalPlace(newValue, 3)) {
e.preventDefault();
return false;
}
});
function hasDecimalPlace(value, x) {
var pointIndex = value.indexOf('.');
return pointIndex >= 0 && pointIndex < value.length - x;
}
Original answer
jsFiddle
$('.decimal').keypress(function (e) {
var character = String.fromCharCode(e.keyCode)
var newValue = this.value + character;
if (isNaN(newValue) || parseFloat(newValue) * 100 % 1 > 0) {
e.preventDefault();
return false;
}
});
Note that parseFloat(newValue) * 100 % 1 > 0 evaluates to true if newValue contains a number that has more than 2 decimal places.
$("#salary").keyup(function(){
var number = ($(this).val().split('.'));
if (number[1].length > 2)
{
var salary = parseFloat($("#salary").val());
$("#salary").val( salary.toFixed(2));
}
});
http://jsfiddle.net/calder12/fSQpc/
Stop letters from going in the box, you'll have to put the two together I haven't time.
if (this.value.match(/[^0-9]./g)) {
this.value = this.value.replace(/[^0-9]./g, '');
return false;
}
Another Possible Solution(Demo):
Number.prototype.toFixedDown = function(digits) {
var n = this - Math.pow(10, -digits)/2;
n += n / Math.pow(2, 53); // added 1360765523: 17.56.toFixedDown(2) === "17.56"
return n.toFixed(digits);
}
$( function() {
$('.two-digits').keyup(function(){
if($(this).val().indexOf('.')!=-1){
if($(this).val().split(".")[1].length > 2){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixedDown(2);
}
}
return this; //for chaining
});
});
This might be helpful to some. I mixed the answers of this guy, #Tats_innit
from https://stackoverflow.com/a/10514166/5382523 and #Rick Calder above.
EDIT
also from this guy, isJustMe from https://stackoverflow.com/a/17289322
for the parseFloat with "|| 0". Because if the input's field is null or zero "NaN" is shown and you can't delete it.
HTML
<input type="text" name="txt_prod_price" id="txt_prod_price" class="form-control price" maxlength="20" placeholder="">
JAVASCRIPT (JQUERY)
$('.price').keypress(function(event) {
if(event.which < 46 || event.which > 59) {
event.preventDefault();
} // prevent if not number/dot
if(event.which == 46 && $(this).val().indexOf('.') != -1) {
event.preventDefault();
} // prevent if already dot
var number = ($(this).val().split('.'));
if (number[1].length > 2)
{
var price = parseFloat($("#txt_prod_price").val()) || 0;
$("#txt_prod_price").val(price.toFixed(2));
}
});
the "price" is pre-defined.
Note: still have buggy inputs but still kickin'. (y)
More info about toFixed - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
I did it this way: Provided a class allow-only-numbers, for your input then:
var numberOfDecimals = 2;
$(document).on("input", ".allow-only-numbers", function () {
var regExp = new RegExp('(\\.[\\d]{' + numberOfDecimals + '}).', 'g')
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').replace(regExp, '$1');
});

How to validate allow minus(-) and only numbers in input textbox using Jquery?

How to validate in an Amount input field?
Allow minus (Negative) sign only once in the text box. For, eg, -10.00. Don't allow other special characters because it's an amount field.
It should not allow alphabet letters. Allow only numbers.
Decimal(.) should be only once in the text box.
I've wrote this just now based on your conditions, test it below:
Update:
Modified to work both on jquery and in javascript inline
// This is a middleware that takes as parameter "decimals" which is by default 2
currencyNumber = function(decimals) {
if (typeof decimals !== 'number') {
decimals = 2;
}
return function(e) {
var input = $(this instanceof Window ? e : e.currentTarget);
var value = $.trim(input.val());
var hasNegativeNumber = value.substr(0, 1) === '-' ? '-' : '';
var nextValue = value
.replace(/\.+/g, '.')
.replace(/[^0-9\.]+/g, '');
if (nextValue === '.' || (nextValue.length > 1 && nextValue === "00")) {
nextValue = '';
}
var dotsFound = nextValue.split('.').filter(function(i) {
return i.length;
});
var afterDot = '';
var beforeDot = '';
if (dotsFound.length > 1) {
beforeDot = dotsFound[0];
dotsFound.splice(0, 1);
afterDot = dotsFound.join('');
nextValue = +(beforeDot) + '.' + afterDot.substr(0, decimals);
}
if (nextValue.substr(nextValue.length - 1, 1) === '.') {
input.one('change', function() {
if (nextValue.substr(nextValue.length - 1, 1) === '.') {
nextValue = nextValue.substr(0, nextValue.length - 1);
input.val(hasNegativeNumber + nextValue);
}
$(this).off('change');
})
} else {
input.off('change')
}
input.val(hasNegativeNumber + nextValue);
};
}
// Here is where you call the middleware
$("#amount").on("keyup", currencyNumber(3));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="banner-message">
Test your number (bind is from jquery):
<input id="amount" type='text' />
<br /> Test your number (bind is from javascript inline):
<input id="amount-inline" onkeyup="currencyNumber(3)(this);" type='text' />
</div>
Edited: I guess this is what you are looking for. Found this in jsfiddle.net. No plugin needed.
HTML:
<input type="text" maxlength="10" id="myInput">
Javascript
var input = document.getElementById("myInput");
input.onkeypress = function(e) { e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
// Allow non-printable keys
if (!charCode || charCode == 8 /* Backspace */ ) {
return;
}
var typedChar = String.fromCharCode(charCode);
// Allow numeric characters
if (/\d/.test(typedChar)) {
return;
}
// Allow the minus sign (-) if the user enters it first
if (typedChar == "-" && this.value == "") {
return;
}
// In all other cases, suppress the event
return false;
};

Aplying JQuery mask dynamically

I have a text field and when the user types the first char I have to apply one of two masks.
The rules are:
if the user types '#' the mask to be applied is '#9999999999'.
If the user types a number the mask to be applied is '999.999.999-99'.
The JavaScript that I generated is
(function () {
var oldVal;
$('#id').on('keypress paste textInput input', function () {
var val = this.value;
if ((val != oldVal) && (val.length == 1)) {
oldVal = val;
if(oldVal == '#'){
$('#id').mask('999999999');
$('#id').val(oldVal)
}else{
$('#id').mask('999.999.999-99');
$('#id').val(oldVal)
}
}else if(val.length == 0) {
$('#id').unmask();
}
});
}());
Fortunately the mask is correctly applied. The problem is that the first char is being lost.
Example:
When I type 012.345.678-99 the field gets _12.345.678-99.
Similarly when I type #2001120001 the field gets _2001120001.
What I'm doing wrong?
Thank you!
I'm not sure if this is what you were looking for, but...
The plugin tries to apply the mask on every keypress. Altering the mask a little bit (and the translation, because "#" is considered to be a digit placeholder) lets the plugin handle the whole input line and mask it.
if (oldVal == '#') {
$('#id').mask('#999999999', {"translation": {"#": null}});
$('#id').val(oldVal);
} else {
$('#id').mask('999.999.999-99');
$('#id').val(oldVal);
}
It works in this fiddle. http://jsfiddle.net/FfR8j/2/
Again, not sure if that's what you were looking for.
I used following code to mask Australian contact number field. Masking rules will be updated as the user enter first two or four digits:
// contactNumberOptions
var contactNumberOptions = {onKeyPress: function(cep, e, field, options){
var masks = ['00 0000 0000', '0000 000 000', '0000 0000'];
var prefix2 = cep.substring(0, 2);
var prefix3 = cep.substring(0, 5);
var prefix4 = cep.substring(0, 4);
mask = masks[2];
if( prefix2 == '02' || prefix2 == '03' || prefix2 == '07' || prefix2 == '08'){
mask = masks[0];
} else if( prefix2 == '04'){
mask = masks[1];
} else if( prefix4 == '1800' || prefix4 == '1900' || prefix4 == '1902'){
mask = masks[1];
} else {
mask = masks[2];
}
jQuery('input[name=contact-number]').mask(mask, options);
}};
jQuery('input[name=contact-number]').mask('0000 0000', contactNumberOptions);

How to prevent keypress two digits after a decimal number?

I have got a task to prevent keypress two digits after a decimal number.
My jquery file is
$(function(){
$('#name').bind('paste', function(){
var self = this;
setTimeout(function() {
if(!/^[a-zA-Z]+$/.test($(self).val()))
$(self).val('');
}, 0);
});
$('#salary').bind('paste', function(){
var self = this;
setTimeout(function() {
if(!/^\d*(\.\d{1,2})+$/.test($(self).val()))
$(self).val('');
}, 0);
});
$('.decimal').keyup(function(){
var val = $(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9]./g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
$(this).val(val);
});
});
My html page is
<b>Name</b>
<input type="text" id="name" /><br/>
<b>Salary</b>
<input type="text" id="salary" class="decimal" />
here i want only write 2 digits after decimal,how can i do this?
You can see my code in http://jsfiddle.net/V6s4B/
You can handle the key event before keyup on keypress, if the input is not to our liking we can disable the event from occurring. Something like this:
Update
Unfortunately my original answer below fails on certain numbers that can't be represented accurately as a float. Here is another solution that checks the position of the '.' character against the length of the string with a handy helper function.
jsFiddle
$('.decimal').keypress(function (e) {
var character = String.fromCharCode(e.keyCode)
var newValue = this.value + character;
if (isNaN(newValue) || hasDecimalPlace(newValue, 3)) {
e.preventDefault();
return false;
}
});
function hasDecimalPlace(value, x) {
var pointIndex = value.indexOf('.');
return pointIndex >= 0 && pointIndex < value.length - x;
}
Original answer
jsFiddle
$('.decimal').keypress(function (e) {
var character = String.fromCharCode(e.keyCode)
var newValue = this.value + character;
if (isNaN(newValue) || parseFloat(newValue) * 100 % 1 > 0) {
e.preventDefault();
return false;
}
});
Note that parseFloat(newValue) * 100 % 1 > 0 evaluates to true if newValue contains a number that has more than 2 decimal places.
$("#salary").keyup(function(){
var number = ($(this).val().split('.'));
if (number[1].length > 2)
{
var salary = parseFloat($("#salary").val());
$("#salary").val( salary.toFixed(2));
}
});
http://jsfiddle.net/calder12/fSQpc/
Stop letters from going in the box, you'll have to put the two together I haven't time.
if (this.value.match(/[^0-9]./g)) {
this.value = this.value.replace(/[^0-9]./g, '');
return false;
}
Another Possible Solution(Demo):
Number.prototype.toFixedDown = function(digits) {
var n = this - Math.pow(10, -digits)/2;
n += n / Math.pow(2, 53); // added 1360765523: 17.56.toFixedDown(2) === "17.56"
return n.toFixed(digits);
}
$( function() {
$('.two-digits').keyup(function(){
if($(this).val().indexOf('.')!=-1){
if($(this).val().split(".")[1].length > 2){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixedDown(2);
}
}
return this; //for chaining
});
});
This might be helpful to some. I mixed the answers of this guy, #Tats_innit
from https://stackoverflow.com/a/10514166/5382523 and #Rick Calder above.
EDIT
also from this guy, isJustMe from https://stackoverflow.com/a/17289322
for the parseFloat with "|| 0". Because if the input's field is null or zero "NaN" is shown and you can't delete it.
HTML
<input type="text" name="txt_prod_price" id="txt_prod_price" class="form-control price" maxlength="20" placeholder="">
JAVASCRIPT (JQUERY)
$('.price').keypress(function(event) {
if(event.which < 46 || event.which > 59) {
event.preventDefault();
} // prevent if not number/dot
if(event.which == 46 && $(this).val().indexOf('.') != -1) {
event.preventDefault();
} // prevent if already dot
var number = ($(this).val().split('.'));
if (number[1].length > 2)
{
var price = parseFloat($("#txt_prod_price").val()) || 0;
$("#txt_prod_price").val(price.toFixed(2));
}
});
the "price" is pre-defined.
Note: still have buggy inputs but still kickin'. (y)
More info about toFixed - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
I did it this way: Provided a class allow-only-numbers, for your input then:
var numberOfDecimals = 2;
$(document).on("input", ".allow-only-numbers", function () {
var regExp = new RegExp('(\\.[\\d]{' + numberOfDecimals + '}).', 'g')
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').replace(regExp, '$1');
});

Allows only one "." in Javascript during KeyPress

How to allow only one "." in javascript during Keypress?
I have a code here:
function allowOneDot(txt) {
if ((txt.value.split(".").length) > 1) {
//here, It will return false; if the user type another "."
}
}
I will reiterate what I said in my comment before the answer:
And what if the user pastes in a bunch of periods? What if they edit the javascript in their console to completely ignore this check? Make sure you are handling validation correctly and not making too many simplifications.
Now that we're proceeding at our own risk, here's how you would not allow a user typing more than one . (period) in a textbox:
document.getElementById('yourTextboxIDHere').onkeypress = function (e) {
// 46 is the keypress keyCode for period
// http://www.asquare.net/javascript/tests/KeyCode.html
if (e.keyCode === 46 && this.value.split('.').length === 2) {
return false;
}
}
Working demo
If you really want to allow one dot, even in the event of a user pasting text inside it, you should use keyup, not keypress, and you could keep your last text value in case you need to restore it.
The drawback though, is that the input value will have already been changed, and you will see it getting corrected as you type.
(function() {
var txt = document.getElementById('txt');
var prevValue = txt.value;
function allowOneDot(e) {
var dots = 0;
var length = txt.value.length;
var text = txt.value;
for(var i=0; i<length; i++) {
if(text[i]=='.') dots++;
if(dots>1) {
txt.value = prevValue;
return false;
}
}
prevValue = text;
return true;
}
txt.onkeyup = allowOneDot;
})();
I solved this question for the multipurpose use of decimal, number & alphanumeric field types.
For field types 'number' and 'alphanum', parameter l (lower L) is the string length allowed. For type 'decimal', it specifies the allowed number of decimal places.
function allowType(e, o = 'number', l = false) {
let val = e.target.value;
switch (o) {
case 'alphanum':
if (l) {
val = val.substr(0, l).replaceAll(/[^0-9a-zA-Z]/gmi, '');
} else {
val = val.replaceAll(/[^0-9a-zA-Z]/gmi, '');
}
break;
case 'number':
if (l) {
val = val.substr(0, l).replaceAll(/[^0-9]/gmi, '');
} else {
val = val.replaceAll(/[^0-9]/gmi, '');
}
break;
case 'decimal':
let i = val.search(/\./gmi);
if (val.length === 1) {
val = val.replaceAll(/[^0-9]/gmi, '');
}
if (i >= 0) {
if (l) {
val = val.substr(0, i + 1) + val.substr(i).substr(0, l + 1).replaceAll(/\./gmi, '');
} else {
val = val.substr(0, i + 1) + val.substr(i).replaceAll(/\./gmi, '');
}
}
val = val.replaceAll(/[^0-9.]/gmi, '');
break;
}
e.target.value = val;
}
<input type="text" oninput="allowType(event, 'decimal', 2)" placeholder="decimal">
<input type="text" oninput="allowType(event, 'number', 10)" placeholder="number">
<input type="text" oninput="allowType(event, 'alphanum', 5)" placeholder="alphanumeric">
<input type="text" id="test" onkeyup="floatOnly(this);"/>
<script>
function floatOnly(i){
{
if ((i.value).length > 0){else{i.value = i.value.replace(".." , ".");i.value = i.value.replace("..." , ".");i.value = i.value.replace(/[^0-9\.]/g , "");}}else{i.value = i.value="0";}}<script>

Categories