[英]What's the correct regex to allow a dash symbol when using the jquery.validator.addMethod?
I just can't get this figured out. 我只是想不通。 I'm using
jquery.validator.addMethod
. 我正在使用
jquery.validator.addMethod
。 Currently I have the following: 目前,我有以下内容:
jQuery.validator.addMethod("alphanumeric", function(value, element) {
return this.optional(element) || /^\w+$/i.test(value);
}, "Letters, numbers, and underscores only please");
This allows letters, underscores and numbers. 这样可以使用字母,下划线和数字。 But what I'd need to allow instead of underscore would be a dash (
-
). 但是我需要允许的是下划线(
-
)而不是下划线。
I'm very new to regex and I've been trying to figure out this simple problem but I just can't find a way to do it. 我对regex还是很陌生,我一直试图找出这个简单的问题,但我找不到解决方法。 Any help would be much appreciated.
任何帮助将非常感激。
It's called "dash" try this: 这叫做“破折号”试试这个:
jQuery.validator.addMethod("alphanumeric", function(value, element) {
return this.optional(element) || /^[a-z0-9\-]+$/i.test(value);
}, "Letters, numbers, and dashes only please");
You could achieve the same result by specifying a pattern
rule and message as follows: 通过指定如下所示的
pattern
规则和消息,可以达到相同的结果:
$('form').validate({ rules: { alphanumdash: { required: true, pattern: /^[a-z0-9\\-]+$/ } }, messages: { alphanumdash: { required: 'AlphaNumDash is required', pattern: 'Letters, numbers, and dashes only please' } } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.min.js"></script> <form id="test"> <input type="text" name="alphanumdash" /><br/> <input type="submit" /> </form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.