Sachin Nayak
Sachin Nayak

Reputation: 3

javascript to allow only negative and positive numbers and decimal upto 6 digits on keypress

I need to validate a textbox in my cshtml page to accept only negative or positive numbers and upto 6 decimal places. This is what I have tried so far.

function AcceptUptoSixDecimalPlacesWithNegative(event, elem) {

if ((event.which != 46 || $(elem).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
    if (event.keyCode !== 8 && event.keyCode !== 46 && event.keyCode !== 9 && event.keyCode !== 0 && event.keyCode !== 45) { //exception
        event.preventDefault();
    }
}

var text = $(elem).val();

if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.')).length > 6)) {
    if (event.keyCode !== 8 && event.keyCode !== 46 && event.keyCode !== 9) { //exception
        event.preventDefault();
    }
}

This is helping me achieve six digits after decimal point but then it allows all special characters and alphabets too.

Any help with this problem would be appreciated.

Thanks.

Upvotes: 0

Views: 13959

Answers (5)

pawel
pawel

Reputation: 36965

  1. Don't validate the keys pressed. There are many ways to change input value. Handle the oninput event.
  2. You may treat the value as a string and validate using a regular expression, but I think it's better to combine string and number-related functions

For example:

<input type="number" step="any" oninput="validate(this)" />  

function validate(input){
  var number = parseFloat(input.value);
  if( number == input.value && input.value.length <= number.toFixed(6).length ){ /* valid! */ }
}

http://jsfiddle.net/tto2yvwj/

Upvotes: -1

daxeh
daxeh

Reputation: 1085

Here are a list of functions to help in your question:

  1. Math.sign() checks if its a positive/0, negative/0 and NaN
  2. Number MDN contains a list of number functions
  3. parseFloat()
  4. count digits after decimal post or regex ie. \d+([.\d{1,6}]*)\

In your context, a combination of validations in the following example:

let x = elem;
if(Math.sign(x) === 1 || Math.sign(x) === -1) && ...
// decimal validations

Hope this helps.

Upvotes: 0

Peter Fischaleck
Peter Fischaleck

Reputation: 342

You could check the value with Regex:

var re = /^-?\d*\.?\d{0,6}$/; 
var text = $(elem).val();

var isValid = (text.match(re) !== null);

The Regex means:

^ : beginning of string

-? : one or zero "-"

\d* : 0 to infinite numbers

\.? : 0 or 1 "."

\d{0,6} : from 0 to 6 numbers

$ : End of string

Upvotes: 6

Pudd
Pudd

Reputation: 447

You could use the isNaN() function of JavaScript.

var inputPrevValue = "";

$(document).ready(function () {
    $("#numbersOnly").change(function () {
        if (isNaN($(this).val()) || $(this).val().length > 6) {
            $(this).val(inputPrevValue);
        } else {
            inputPrevValue = $(this).val();
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" id="numbersOnly">

This is a (very simplistic) example that tests if the input is a number less than 6 characters in length. If not, it'll revert it to the last acceptable value.

Upvotes: 1

Raghava Rudrakanth P V
Raghava Rudrakanth P V

Reputation: 131

***Adding Comment as no access yet!!!

Try Regex "^[0-9]+(.[0-9]{1,2})?$" to verify the text and then proceed with logic. js code:

var patt = new RegExp("^[0-9]+(.[0-9]{1,6})?$");
var res = patt.test(str);

if res is true then proceed else return false;

Upvotes: 0

Related Questions