正则表达式,允许数字,空格,加号,连字符和括号 [英] Regular expression which allows numbers, spaces, plus sign, hyphen and brackets

查看:1029
本文介绍了正则表达式,允许数字,空格,加号,连字符和括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jquery验证器,我在其中添加了一个方法来验证字符串,该字符串只允许数字,空格,加号,连字符和括号。数字在字符串中是必填项,但其他租船人是可选的。

I am using jquery validator where I have added a method to validate a string which allow only numbers, spaces, plus sign, hyphen and brackets. Number is mandatory in the string but other charterer is optional.

我在jquery validor中添加方法的代码:

My code for adding method in jquery validor:

jQuery.validator.addMethod( "regex", function(value, element, regexp) {
        var re = new RegExp(regexp);
        return this.optional(element) || re.test(value);
    },
    "Please check your input."
);

以下规则代码:

rules: {
myfield: {
    required: true,
    regex: "[0-9]+" // want to add regular expression but I wrote only for digit which works but do not understand how to reach at my requirements.
 },
}


推荐答案

您可以将所需字符添加到字符类中

You can add the required characters into character class as

/^(?=.*[0-9])[- +()0-9]+$/

正则表达式演示

正则表达式解释


  • (?=。* [0-9])积极向前看。确保至少有一位数

  • (?=.*[0-9]) postive look ahead. Ensures that there is atleast one digit

[ - +()0-9] + 匹配数字,空格,加号,连字符和括号

[- +()0-9]+ matches numbers, spaces, plus sign, hyphen and brackets

OR

如果您不愿意使用预测。你可以在没有它们的情况下写一个lenghier正则表达式

If you are reluctant in using look aheads. You could write without them a lenghier regex as

/^[- +()]*[0-9][- +()0-9]*$/

这篇关于正则表达式,允许数字,空格,加号,连字符和括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆