I have an input field which is limited to 6 characters. How can I validate my input field so that a user can't put more than one decimal point (i.e. 19..12), plus it can only be to two decimal places as well (i.e. 19.123)?
This is my input field
<input type="text" name="amount" id="amount" maxlength="6" autocomplete="off"/><span class="paymentalert" style="color:red;"></span>
Here is my validation script.
$(function(){
$("#amount").keypress( function(e) {
var chr = String.fromCharCode(e.which);
if (".1234567890NOABC".indexOf(chr) < 0)
return false;
});
});
$("#amount").blur(function() {
var amount = parseFloat($(this).val());
if (amount) {
if (amount < 40 || amount > 200) {
$("span.paymentalert").html("Your payment must be between £40 and £200");
} else {
$("span.paymentalert").html("");
}
} else {
$("span.paymentalert").html("Your payment must be a number");
}
});
Jonah
This should do :
var ok = /^\d*\.?\d{0,2}$/.test(input);
(if I correctly understood that you don't want more than 2 digits after the dot)
The code thus would be :
$("#amount").blur(function() {
var input = $(this).val();
if (/^\d*\.?\d{0,2}$/.test(input)) {
var amount = parseFloat(input);
if (amount < 40 || amount > 200) {
$("span.paymentalert").html("Your payment must be between £40 and £200");
} else {
$("span.paymentalert").html("");
}
} else {
$("span.paymentalert").html("Your payment must be a number");
}
});
Assuming that:
There MUST have 2 digits after a decimal point, and
There must be at least 2 digits before the decimal point, but no more than 3 digits
The code you would use to match it would be:
var value = $(this).val;
value.match(/^\d{2,3}(\.\d{2})?$/i);
It would be much easier if you used the Masked Input Plugin for jQuery.
Related
I have this one line of code:
if ($val === "" || ($val.split(".")[1] || "").length > 2)
Thanks to some help from the good people here. But this line of code counts numbers over 2 decimal places even if the numbers are all zeroes.
The problem with this is people can add 2.00 which is fine but not 2.000 which is the same number. So I am looking to add one more || statement that allows people to add multiple zero decimal places.
The entire code is this:
$(document).ready(function() {
$("#submitCalculation").click(function() {
$(".checkLength").each(function() {
$val = $(this).val();
if ($val === "" || ($val.split(".")[1] || "").length > 2) {
$(this).popover({
html: true,
placement: "bottom",
content: '<textarea class="popover-textarea"></textarea>',
template: '<div class="popover"><div class="arrow"></div>'+
'<div class="row"><div class="col-3 my-auto"><i class="fas fa-exclamation-triangle" id="invalid-input7">'+
'</i></div><div class="popover-content col-9">Enter a value between 2 and 50 m with up to 2 decimal places.'+
'</div></div>'
});
$(this).popover("show");
$(this).click( function() {
$(this).popover("hide");
});
}
})
})
})
It checks a number input for validity, if the field is blank, a popover tells them and the script stops there. If the field has too many decimal places, the poppver tells them and the script stops there. But, the problem now lies with the fact that people can add multiple zero decimal places, the script doesn't stop, but the popover still pops up.
Looking forward to your help on this one, it's been troubling me a while.
This should do the job:
console.log("my answer:","1.2345,0.0103,4.56,2.3400,123.22000,234"
.split(",").map(val=>{
let m=val.match(/\.\d\d(.*)/);
return val+': '+!!(m&&m[1]>0)
}) );
// the following is Barmar's method which gets it wrong in 4 cases:
console.log("Barmar's answer:","1.2345,0.0103,4.56,2.3400,123.22000,234"
.split(",").map(val=>
val+': '+!!(val == "" || val.match(/\.\d{0,2}[1-9]+/))) );
In your script you would need to replace
$val = $(this).val();
if ($val === "" || ($val.split(".")[1] || "").length > 2) { ...
with
$val = $(this).val();
let m=$val.match(/\.\d\d(.*)/);
if (!!(m&&m[1]>0)) { ...
Convert the number to a float before checking it, as this will discard trailing zeroes after the decimal point. Then use a regular expression to check for too many digits after the decimal. You can also use isNaN to check if it's not a number at all.
$(document).ready(function() {
$("#submitCalculation").click(function() {
$(".checkLength").each(function() {
const $val = $(this).val();
let valid = true;
const valFloat = parseFloat($val);
if (isNaN(valFloat)) {
valid = false;
} else if (/\.\d{3}/.test(valFloat.toString())) {
valid = false;
}
if (!valid) {
console.log("Invalid input");
} else {
console.log("Valid input");
}
})
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="checkLength">
<button id="submitCalculation">Check</button>
I have numeric fields on form were users can occasionally type a decimal value with decimal place but no values on one side.
i.e the intended value to be entered can be 5 or 5.00
but occasionally a user can type .5 OR 5.
so in this case if they have left out values before the decimal place, I would like to add/append the value with 0.5 or if they have left out the values after the decimal place I would like to add/append with 5.00
.5 => 0.5
5. => 5.00
Ideally the input value would then be updated onBlur or when user clicks/tabs away from that field or anywhere else on the page. My quick attempt at this is currently as follows (untested)
$('input').on('blur', function () {
var currentValue = $(this).val();
var splitNumber = currentValue.split('.');
var beforeDecimal = splitNumber[0];
var afterDecimal = splitNumber[1];
if (beforeDecimal.length < 1)
{
//add one zero before decimal
}
if (afterDecimal.length < 1)
{
//add two zeros after decimal
}
});
Instead you can just use a combination of parseFloat and toFixed
parseFloat('.5') --> 0.5
parseFloat('5.') --> 5
$('input').on('blur', function() {
let value = this.value;
if(!isNaN(value)) {
let parsedValue = parseFloat(value);
$('.output').text(parsedValue.toFixed(2));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<input type="text" />
<span>Output: </span>
<span class="output">
</span>
Here is an example may help you:
var myNum1 = .5;
var myNum2 = 5.;
function pad(num){
return num.toFixed(2);
}
console.log(pad(myNum1));
console.log(pad(myNum2));
I have a single input field where the user can only enter a number between 2 AND 50. Anything above or below is invalid. It also MUST be a numeric value.
What I have so far is this:
$('#searchTimes').click(function() {
if($('#replyNumber').val()<=0) {
alert("Please select a value greater than 0 for number of guests");
$('#replyNumber').focus();
return;
}
if($('#replyNumber').val()>=51) {
alert("Please select a value less than or equal to 50 for number of guests");
$('#replyNumber').focus();
return;
}
if(isNaN($('#replyNumber').val())) {
alert("Please enter a numeric value only");
$('#replyNumber').focus();
return;
}
});
Is there a better more efficient way of writing that ^.
Also ... IF all of those IF statements are not true then I need to perform another function. How can I add that in?
_isValidNumber(number) {
var message;
var isValid;
switch(number){
case number >= 51:
message = "Please select a value less than or equal to 50 for number of guests";
isValid = false;
case number <= 0:
message = "Please select a value greater than 0 for number of guests";
isValid = false;
case isNumeric(number):
var message = "Please enter a numeric value only";
isValid = false;
default:
return true;
}
alert(message);
$('#replyNumber').focus()
return isValid;
}
function isNumeric(num){
return !isNaN(num)
}
var number = $('#replyNumber').val();
var numberIsValid = _isValidNumber(number);
I would try to abstract out duplicate code, like this:
<input id="replyNumber" >
<button id="searchTimes">click</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$('#searchTimes').click(function() {
var val = $('#replyNumber').val()
if(val<=0) showErr("Please select a value greater than 0 for number of guests");
else if(val>=51) showErr("Please select a value less than or equal to 50 for number of guests");
else if(isNaN(val))showErr("Please enter a numeric value only");
});
function showErr(msg){
alert(msg);
$('#replyNumber').focus();
}
</script>
This is what you need :D
$('#searchTimes').on('click',function() {
var do_function = 1;
if (!$.isNumeric($('#replyNumber').val())) {
alert("Please enter a numeric value only");
$('#replyNumber').focus().select();
} else if (+$('#replyNumber').val() < 2) {
alert("Please select a value at least 2 for number of guests");
$('#replyNumber').focus().select();
} else if (+$('#replyNumber').val() > 50) {
alert("Please select a value no more than 50 for number of guests");
$('#replyNumber').focus().select();
} else {
do_function = 0;
}
if (do_function) {
call_some_function();
}
});
Good luck!
Use HTML5 min and max attributes and an input of type number (which covers the numeric part you mentioned). Use rangeOverflow and rangeUnderflow Validity Properties to check your input and present the proper error (or custom error) messages.
Try the below snippet using the following values (null (empty input),1,55) and check the custom error messages created.
function validateInput() {
var txt = "";
if (document.getElementById("inp1").validity.rangeOverflow) {
txt = "Value larger than acceptable!";
}
if (document.getElementById("inp1").validity.rangeUnderflow) {
txt = "Value smaller than acceptable";
}
if (document.getElementById("inp1").validity.valueMissing) {
txt = "Please type a number!";
}
document.getElementById("output").innerHTML = txt;
}
document.getElementById("btn").addEventListener("click", function(){
validateInput();
});
<form>
<input type="number" id="inp1" name="numberInput" min="2" max="50" required>
<button id="btn">go</button>
</form>
<div id="output"></div>
I have one amount field in that i want to restrict user after decimal they can not use more than two values:
After decimal there should be only two values that are option.
User can not type more than one decimal in the field.
I am using following regix for that its not working can any one help.
function validate(evt) {
if (evt.keyCode == 8) { return true; }// for backspace problem in mozilla
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9 ]|\,\d{1,2}/;
if (!regex.test(key))
{
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
This can actually be accomplished using HTML only by setting the STEP and MAX of your numeric field such as
<form>
<input type="number" name="myNumber" required=true step=".01">
<button>send</button>
</form>
please let me know if this is what your looking for but this will mean that any value entered must be numeric(thus only 1 decimal point) it must be less than or equal to 1 (you can set to .99 if you dont want to include 1) and it must be an increment of .01(so it can only have 2 decimal places.
Just re-read your question you can remove the max(i thought i read no more than 1.0)
var previousValue;
function numberChanged(element){
if(validateMe(element)==false){
element.value=previousValue;
}else{
previousValue=element.value;
}
function validateMe(element){
wholeNumber=element.value.split(".")[0];
if(element.value.split(".").length==1){
if(wholeNumber<-1 || > 999999999){
return false;
}
}else if(element.value.split(".").length==2){
decimalValue=element.value.split(".")[1];
if(decimalValue>-1 && decimalValue<100){
if(wholeNumber<-1 || > 999999999){
return false;
}
}else{
return false;
}
}else{
return false;
}
}
<input type="text" id="myNumber" onChange="numberChanged(this)" />
I believe I have a fairly simple problem, but I am unfortunately unable to resolve it. I have searched for a while and tried several different variations of this code but cannot seem to get it to work.
All I am trying to do is check and see if my input value has a alpha character in it opposed to a number.
Here is my js function:
function checkLetters(input) {
var numOnly = /^[0-9]+$/;
var hasLetters = false;
if (!input.value.match(numOnly)) {
hasLetters = true;
}
return hasLetters;
}
and here is the code calling it:
<input type="text" name="cc_number" size="13" maxlength="11" onblur="
if(checkLength(cc_number.value) == true) {
alert('Sorry, that is not a valid number - Credit Card numbers must be nine digits!');
} else if (checkLetters(cc_number.value) == true) {
alert('Credit Card number must be numbers only, please re-enter the CC number using numbers only.');
}">
Any help or suggestions would be appreciated.
It looks like you're trying to validate credit card input. May I suggest a different approach?
function checkCardInput(input,errorId) {
var errorNoticeArea = document.getElementById(errorId);
errorNoticeArea.innerHTML = '';
if(!input.value) {
errorNoticeArea.innerHTML = 'This field cannot be left blank.';
return;
}
if(!input.value.match(/[0-9]/)) {
errorNoticeArea.innerHTML = 'You may only enter numbers in this field.';
input.value = '';
return;
}
if(input.value.length != 9) {
errorNoticeArea.innerHTML = 'Credit card numbers must be exactly 9 digits long.';
return;
}
}
See this jsFiddle for an example use.
You're passing cc_number.value as input, but then referencing input.value.match(), which works out to:
cc_number.value.value.match();
Just pass cc_number:
if (checkLetters(cc_number)) {
...
}