简体   繁体   English

使用! 用于正则表达式编号验证

[英]Using ! for Regex Number Validation

I am trying to display an error message when the user enters anything other than a number using jQuery and regex. 当用户使用jQuery和regex输入数字以外的其他内容时,我试图显示一条错误消息。 How do I do this? 我该怎么做呢?

if( $(this).val().match(/^[0-9]$/) ){
    alert("Wrong input. Only numbers allowed");
}

I tried using ! 我尝试使用! but it did not work and I got no error message 但它没有用,并且我没有错误信息

if( $(this).val().match(/![0-9]/) ){
    alert("Wrong input. Only numbers allowed");
}

Do it like this : 像这样做 :

if( /\D/.test($(this).val()) ){
    alert("Wrong input. Only numbers allowed");
}

\\D is any character that isn't a digit ( \\d is a digit). \\D是不是数字的任何字符( \\d是数字)。

Don't use match when you want to test if a string matches a pattern: it builds an useless array. 当您要测试字符串是否与模式match时,请不要使用match :它会建立一个无用的数组。 What you need is test . 您需要的是test

Now, let's imagine you want to test if the user entered a number, not just a sequence of digits. 现在,让我们假设您要测试用户是否输入了一个数字,而不仅仅是一个数字序列。 A number can be written with a sign, an exponent, a dot, etc. The proper way to test for that isn't to use a regex: 可以用一个符号,一个指数,一个点等来写一个数字。进行测试的正确方法是不使用正则表达式:

var s = $(this).val();
if (s != +s) {
    alert("Wrong input. Only numbers allowed");
}

+s is the conversion of s to a number, NaN if it isn't possible. +ss到数字的转换,如果不可能,则转换为NaN

Negate the range, not the regex itself: 取反范围,而不是正则表达式本身:

if( $(this).val().match(/[^0-9]/) ){
    alert("Wrong input. Only numbers allowed");
}

That will match any string containing non-numbers. 这将匹配包含非数字的任何字符串。

To deal with both integer and floating point numbers.. 处理整数和浮点数。

if( !/^\d+(?:\.\d+)?$/.test($(this).val()) ){
    alert("Wrong input. Only numbers allowed");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM