JavaScript正则表达式(页面范围验证) [英] JavaScript regular expression (Page range validation)

查看:52
本文介绍了JavaScript正则表达式(页面范围验证)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天,我有一项任务是在字段上实施验证,用户可以在该字段中输入要下载的页面范围.

Yesterday I've got a task to implement a validation on the field where user can enter the range of pages that he wants to download.

在阅读了一些教程之后,我创建了一种我认为应该可以使用的模式,但是它不是:(

After reading some tutorials, I've created such pattern which in my opinion should work, but it doesn't :(

能否给我一个提示,指出哪里出了错误,或者应该怎么做才能以更好的方式解决.

Can you give me a hint where is the mistake, or how it should be done in the better way.

<script type="text/javascript">
var patt1=new RegExp("^(\s*\d+\s*\-\s*\d+\s*,?|\s*\d+\s*,?)+$");
document.write(patt1.test("1, 2, 3-5, 6, 8, 10-12"));
</script>

P.S.您可以在此处进行测试: http://www.w3schools.com/js/tryit.asp?filename = tryjs_regexp_test

P.S. You can test it here: http://www.w3schools.com/js/tryit.asp?filename=tryjs_regexp_test

更多示例:

  • 一场比赛
  • 1-2个比赛
  • -2不匹配
  • 1、2-3、4、5-7比赛
  • 1、2、3不匹配
  • 1-2-2不匹配

等...例如在MS Office或Adobe PDF Reader中

etc... like in MS Office or Adobe PDF Reader

推荐答案

您需要对字符串中的反斜杠进行转义,否则JavaScript会将其删除或将其解释为转义序列:

You need to escape the backslashes in the string, or JavaScript will strip them out or interpret them as escape sequences:

var patt1 = new RegExp("^(\\s*\\d+\\s*\\-\\s*\\d+\\s*,?|\\s*\\d+\\s*,?)+$");

这篇关于JavaScript正则表达式(页面范围验证)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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