开发者

This Regex doesn't match things I think that it should

There is a field in my web application into which the user is expected to enter one or more digits separated by one or more periods.

The following is a typical example of what the user may enter:

589327498321.43243214.32421423.

I've written the following JavaScript code to tes开发者_开发技巧t value:

var uid = $(this).val();
var uidRegex = /(^\d|\.$)+/;
var isValid = uidRegex.test(uid);

I'm getting the wrong result. It seems that this code tells me that the entry is valid if the user's entry begins with a digit or period. How can I fix this so that the entire entry must consist exclusively of digits and periods to be valid?


It sounds like the pattern you're looking for is

Number followed by any number dot + number sequences

If so try the following /^(\d)+(\d|\.\d)+$/

EDIT

OP indicated in comments that consecutive dots are legal. Here's the updated regex to account for that as well /^(\d)+(\d|\.)+$/


/^(\d|\.)+$/

That should do it =]


You may also consider:

var uidRegex = /^\d+(\d|\.)+$/;


How about this pattern: /^\d+(\.+\d+)*$/


/^\d[\d\.]*$/
  ^   ^--any number of digits or periods
  |-start with a digit


var uidRegex = /[^\d.]/;
var isValid = ! uidRegex.test(uid);

http://jsfiddle.net/uKm7F/


If you want to disallow a period at the beginning of the string, use this:

var uidRegex = /(?:[^\d.]|^\.)/;
var isValid = ! uidRegex.test(uid);

http://jsfiddle.net/uKm7F/6/


If your field is required (and must contain at least 2 characters), this will do it:

/^(\d)+(\d|\.)*(\d)+$/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜