validate input with decimal precision and scale - javascript

I am trying to create a javascript function which is called on keypress event on a input which does the following:
Input should be a valid decimal with format (5,2) => (XXXXX.YY) which are variable to the function. Input is restricted if user adds any value which does not conform to the format above.
If existing input starts with . append 0 to the starting automatically
HTML
<input type="text" onkeypress="return checkDecimal(event, this, 5, 2);" id="price2" value="27.15">
Javascript
function checkDecimal(evt, item, lenBeforeDecimal, lenAfterDecimal) {
var charCode = evt.which;
var trimmed = $(item).val().replace(/\b^0+/g, "");
if(checkStartsWith(trimmed, '.') == true){
trimmed = '0' + trimmed;
}
//Allow following keys
//8 = Backspace, 9 = Tab
if(charCode == 8 || charCode == 9){
return true;
}
//Only a single '.' is to be allowed
if(charCode == 46){
var dotOccurrences = (trimmed.match(/\./g) || []).length;
if(dotOccurrences != undefined && dotOccurrences == 1){
return false;
}else{
return true;
}
}
if (charCode > 31 && ((charCode < 48) || (charCode > 57))) {
return false;
}
if ($(item).val() != trimmed){
$(item).val(trimmed);}
//Check the start and end length
if(trimmed.indexOf('.') == -1){
if(trimmed.length >= parseInt(lenBeforeDecimal)){
return false;
}
}else{
var inputArr = trimmed.split(".");
if(inputArr[0].length > parseInt(lenBeforeDecimal) || inputArr[1].length >= parseInt(lenAfterDecimal)){
return false;
}
}
return true;
}
function checkStartsWith(str, prefix){
return str.indexOf(prefix) === 0;
}
Issues
If user inputs 12345.9 and then moves the caret position after 5, user is able to add another digit before the decimal 123456.9 which should not be allowed.
If user inputs 1.9 and then remove 1 and add 5, 5 is added at the end and the entered value becomes 0.95 and not 5.9
JS Fiddle

Consider using a regular expression like:
/^(\d{0,5}\.\d{0,2}|\d{0,5}|\.\d{0,2})$/;
that allows everything up to and including your required format, but returns false if the number part is more than 5 digits or if the fraction is more than 2 digits, e.g.:
<input type="text" onkeyup="check(this.value)"><span id="er"></span>
<script>
function check(v) {
var re = /^(\d{0,5}\.\d{0,2}|\d{0,5}|\.\d{0,2})$/;
document.getElementById('er').innerHTML = re.test(v);
}
</script>
You'll need separate validation for the final value, e.g.
/^\d{5}\.\d{2}$/.test(value);
to make sure it's the required format.
I don't understand the requirement to add a leading zero to "." since the user must enter 5 leading digits anyway (unless I misunderstand the question).

Related

jquery - allow only negative, positive or decimal number validation in field

I use this code for positive validation of numbers and decimal. Now I would like to allow also negative numbers and decimals but it is not working. Any idea please?
$('.number_only').keypress(function(e){
return isNumbers(e, this);
});
function isNumbers(evt, element)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (
(charCode != 46 || $(element).val().indexOf('.') != -1) && // “.” CHECK DOT, AND ONLY ONE.
(charCode < 48 || charCode > 57)
)
return false;
return true;
}
I found this but no idea how to implement it jquery - allow only negative, positive or decimal number validation
You can use regex instead to solve your problem, change your method to something like this:
function isNumbers(evt, element)
{
var elementValue = $(element).val();
var regex = /^(\+|-)?(\d*\.?\d*)$/;
if (regex.test(elementValue + String.fromCharCode(evt.charCode))) {
return true;
}
return false;
}

How to executing a validation in text box number format like 44.44

I want to Check the value to both javascript and php ,which one should be like this format 22.22 or 00.44 or 44 or 55.00.
I have the below code.
$(function(){
// $('.pixcel_rate').keypress(function (event) {
// return isNumber(event, this)
// });
$('.pixcel_rate').keypress(function (event) {
return validateFloatKeyPress($(this).val());
});
});
// THE SCRIPT THAT CHECKS IF THE KEY PRESSED IS A NUMERIC OR DECIMAL VALUE.
function validateFloatKeyPress(evt,el) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value.split('.');
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
//just one dot (thanks ddlab)
if(number.length>1 && charCode == 46){
return false;
}
//get the carat position
var caratPos = getSelectionStart(el);
var dotPos = el.value.indexOf(".");
console.log(caratPos);
console.log(dotPos);
if( caratPos >1 && dotPos>-1 && (number[0].length > 1)){
return false;
}
if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
return false;
}
return true;
}
function getSelectionStart(o) {
if (o.createTextRange) {
var r = document.selection.createRange().duplicate()
r.moveEnd('character', o.value.length)
if (r.text == '') return o.value.length
return o.value.lastIndexOf(r.text)
} else return o.selectionStart
}
You can use preg_match in php to see if it matches the pattern.
preg_match("/^\d{2}\.\d{2}$|^\d{2}$/", $val);
This matches either two digits, dot, two digits. Or just two digits.
Example test cases:
https://3v4l.org/G6D8l
You can use regex to achieve this. Below is the regex for your requirement.
https://regex101.com/r/N5gbqs/3/
function validateFloatKeyPress(value) {
//returns null if it doesnt match the given regular expression
return value.toString().match(/^(\d{2}|\d{2}\.\d{2})$/)
}
function validateFloatKeyPress(value) {
//returns false if it doesnt match the given regular expression
return (/^(\d{2}|\d{2}\.\d{2})$/).test(value.toString())
}

allow only 0-100 percent values in textbox

I have a percentage textbox. I want to enter values 0 to 100. Not more than 100 or negative values.
FIDDLE
Please check this fiddle. Here, it is allowing only 2 digit values like 99 only and after 99 it is allowing number of decimals(99..........9999) like this. Need to allow only one decimal point and I can enter 100 also.
Note :
Can Enter 0 to 100 and not negative and not more than 100.00
After decimal I want to enter only 2 digits like, 99.99 only.
Do not allow negative values.
Allow only one decimal point like(9.99 or 99.99). Not (9.......9..9...80099 or 99.......9......9).
<script>
function check(e,value){
//Check Charater
var unicode=e.charCode? e.charCode : e.keyCode;
if (value.indexOf(".") != -1)if( unicode == 46 )return false;
if (unicode!=8)if((unicode<48||unicode>57)&&unicode!=46)return false;
}
function checkLength(){
var fieldVal = document.getElementById('txtF').value;
//Suppose u want 3 number of character
if(fieldVal < 100){
return true;
}
else
{
var str = document.getElementById('txtF').value;
str = str.substring(0, str.length - 1);
document.getElementById('txtF').value = str;
}
}
</script>
<input id="txtF" type="number" onKeyPress="return check(event,value)" onInput="checkLength()" />
<p id="s"></p>
Please help me how can I do this using jQuery or JavaScript.
Updated fiddle. This solves it for now, but the use of step=0.01 may not be what you want. Setting the step to 0.01 allows us to check the validity state of the input.
The validitiy state is not updated an a "before" event so on an "after" event we rollback the input.
<input id="txtF" type="number" onInput="return check(event,value)" min="0" max="100" step="0.01" />
check = function (e,value){
if (!e.target.validity.valid) {
e.target.value = value.substring(0,value.length - 1);
return false;
}
var idx = value.indexOf('.');
if (idx >= 0 && value.length - idx > 3) {
e.target.value = value.substring(0,value.length - 1);
return false;
}
return true;
}
<script>
var point=false;
var count=0;
function check(e,value){
//Check Charater
debugger;
if(count==3)return false;
var unicode=e.charCode? e.charCode : e.keyCode;
if( unicode == 46 && point==true)
return false;
if( unicode == 46 && point==false)
{
point=true;
}
if (unicode!=8)if((unicode<48||unicode>57)&&unicode!=46)return false;
if(point==true)count++;
}
function checkLength(){
var fieldVal = document.getElementById('txtF').value;
//Suppose u want 3 number of character
if(fieldVal <= 100){
return true;
}
else
{
var str = document.getElementById('txtF').value;
str = str.substring(0, str.length - 1);
document.getElementById('txtF').value = str;
}
}
</script>
<input id="txtF" type="number" onKeyPress="return check(event,value)" onInput="checkLength()" />
<p id="s"></p>
http://jsfiddle.net/ySt7S/130/

replace number and symbol with jquery/javascript

Does anyone know how can I replace the number and symbol (excluding dash and single quote)?
Example:
if I have a string "ABDHN'S-J34H##$";
How can I replace the number and symbol to empty and return me value "ABDHN'S-JH" ?
I have the following code to replay all the char and symbol to empty and only return me number
$(".test").keyup(function (e) {
orgValue = $(".test").val();
if (e.which != 37 && e.which != 39 && e.which != 8 && e.which != 46) {
newValue = orgValue.replace(/[^\d.]/g, "");
$(".test").val(newValue);
}
});
You should allow only letters, dash and single quotes, like this:
newValue = orgValue.replace(/[^a-zA-Z'-]/g, "");
Anything else will be replaced by "".
You can use this regex:
string.replace(/^[a-zA-Z'-]+$/, '')
The caret ^ inside a character class [] will negate the match. This regex will convert all characters other than a-z, A-Z, single quote and hyphen to empty
You could replace symbols by skipping them through keycode value on the keyboard.
Link for keycode values for reglar keyboard:
http://www.w3.org/2002/09/tests/keys.html
$("#your control").bind("keydown keyup", doItPlease);
function doItPlease(e)
{
// First 2 Ifs are for numbers for num pad and alpha pad numbers
if (e.which < 106 && e.which > 95)
{
return false; // replace your values or return false
}
else if (e.which < 58 && e.which > 47)
{
// replace your values or return false
} else {
var mycharacters = [8, 9, 33, 34, 35 // get your coders from above link];
for (var i = 0; i < mycharacters.length; i++) {
if (e.which == mycharacters[i]) {
// replace your characters or just
// return false; will cancel the key down and wont even allow it
}
e.preventDefault();
}
"ABDHN'S-J34H##$".replace(/[^\-'\w]/g, '')
"ABDHN'S-J34H##$".replace(/[0-9]|[\'##$]/g, "");

checking for integer input on button click

I am trying to get this Javascript in my application working.
function validateQuantity(field)
{
var value = field.value; //get characters
//check that all characters are digits, ., -, or ""
for(var i=0; i < field.value.length; ++i)
{
var new_key = value.charAt(i); //cycle through characters
if(((new_key <= "0") || (new_key > "9")) &&
!(new_key == ""))
{
alert("Please enter number and greater than 0 only");
return false;
break;
}
return true;
}
}
And I have a input button as below
<input class="buttonToLink" type="submit" value="Update"
onclick="return validateQuantity(document.getElementById('quantity'))"/>
The above code successfully checks the input of all alphabet such as "abc" or alphabet and numeric such as "abcd123" as false.
However, when I put numeric characters first, along with alphabet such as "123abc", it fails -- it does not show the alert.
What did I do wrong with the code, and how can it be fixed?
function validateQuantity(field) {
if (!/^\d+$/.test(field.value)) { // is an integer
alert("Please enter number and greater than 0 only");
return false;
}
return true;
}
The reason your code doesn't work is because you have the return true statement inside the loop. As soon as it sees a valid integer it will return true and break out of the function, ignoring anything that comes after it. Allowing strings like "123abc" for example.
This is probably what you wanted:
function validateQuantity(field)
{
var value = field.value; //get characters
//check that all characters are digits, ., -, or ""
for(var i=0; i < field.value.length; ++i)
{
var new_key = value.charAt(i); //cycle through characters
if(((new_key <= "0") || (new_key > "9")) &&
!(new_key == ""))
{
alert("Please enter number and greater than 0 only");
return false;
break;
}
}
return true;
}
if (parseInt(new_Key) == new_Key) {
//valid
} else { // it will return NaN
//invalid
}
Try parsing the value as an integer, and compare with the original value.
var isAllNumbers = (parseInt(field.value) == field.value);
Perhaps use a jQuery selector, and use a regex to test for numeric.
var isAllNumbers = $("#quantity").val().match(/\d+$/);

Categories