最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

razor - javascript to allow only negative and positive numbers and decimal upto 6 digits on keypress - Stack Overflow

programmeradmin0浏览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.

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.

Share Improve this question edited Apr 29, 2015 at 11:51 Denys Séguret 382k90 gold badges810 silver badges775 bronze badges asked Apr 29, 2015 at 11:50 Sachin NayakSachin Nayak 31 gold badge1 silver badge3 bronze badges 3
  • What happens if the user pastes a value into the field? Won't that bypass your validation? – nnnnnn Commented Apr 29, 2015 at 11:59
  • I have disabled pasting for that field. – Sachin Nayak Commented Apr 29, 2015 at 12:02
  • Have you disabled drag'n'drop too? – nnnnnn Commented Apr 29, 2015 at 12:04
Add a ment  | 

5 Answers 5

Reset to default 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

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

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

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 bination of validations in the following example:

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

Hope this helps.

  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 bine 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/tto2yvwj/

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论