我正在尝试验证文本框的文本输入,以仅允许mm / dd / yyyy输入。基于正则表达式测试器,正则表达式似乎对我想要匹配的内容有效。
导致它失败的原因是什么,我该怎么办呢?
RegEx:(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d
正则表达式测试:http://www.regextester.com/?fam=93828
JSFiddle:https://jsfiddle.net/tL5xx6m9/2/
摘录:
$('.ui.form').form({
inline: true,
fields: {
dateInput: {
identifier: 'dateInput',
rules: [{
type: "regExp[/(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d/]",
prompt: "Please select a valid mm/dd/yyyy date"
}]
},
timeInput: {
identifier: 'timeInput',
rules: [{
type: "regExp[/^(OFF)|([0-1]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])? [APap][mM]$/]",
prompt: "Please select a valid hh:mm AM/PM time"
}]
}
}
});
<script src="https://cdn.jsdelivr.net/jquery/2.1.4/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.1.8/semantic.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.1.8/semantic.min.js"></script>
<form class="ui form attached fluid segment">
<div class="field">
<input name="dateInput" value="01/15/2015" type="text" placeholder="Entry Date">
</div>
<div class="field">
<input name="timeInput" class="field-custom" value="5:30 PM" type="text" id="" placeholder="Entry Time">
</div>
<button class="ui teal button" type="submit">Submit</button>
</form>
答案 0 :(得分:3)
因为你的正则表达式是javascript字符串的一部分,所以任何反斜杠都需要使用双反斜杠进行转义。因此\d
变为\\d
。
此外,使用字符串^
的开头和字符串$
标记的结尾来防止较大字符串(例如01/15/20155
)的匹配成功。
<强>结果:强>
type: "regExp[/^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\\d\\d$/]",
<强>段:强>
$('.ui.form').form({
inline: true,
fields: {
dateInput: {
identifier: 'dateInput',
rules: [{
type: "regExp[/^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\\d\\d$/]",
prompt: "Please select a valid mm/dd/yyyy date"
}]
},
timeInput: {
identifier: 'timeInput',
rules: [{
type: "regExp[/^(OFF)|([0-1]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])? [APap][mM]$/]",
prompt: "Please select a valid hh:mm AM/PM time"
}]
}
}
});
<script src="https://cdn.jsdelivr.net/jquery/2.1.4/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.1.8/semantic.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.1.8/semantic.min.js"></script>
<form class="ui form attached fluid segment">
<div class="field">
<input name="dateInput" value="01/15/2015" type="text" placeholder="Entry Date">
</div>
<div class="field">
<input name="timeInput" class="field-custom" value="5:30 PM" type="text" id="" placeholder="Entry Time">
</div>
<button class="ui teal button" type="submit">Submit</button>
</form>