0

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.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
Sachin Nayak
  • 3
  • 1
  • 1
  • 3

5 Answers5

6

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

1

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.

Pudd
  • 449
  • 3
  • 13
0

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.

Community
  • 1
  • 1
daxeh
  • 1,083
  • 8
  • 12
0

***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;

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

pawel
  • 35,827
  • 7
  • 56
  • 53