Reputation: 10080
I'm trying to validate a text input for a text box to only allow mm/dd/yyyy input. The regex seems to be valid for what I'm trying to match based on regex tester.
What is causing it to fail, and how can I go about fixing it?
RegEx: (0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d
Regex Test: http://www.regextester.com/?fam=93828
JSFiddle: https://jsfiddle.net/tL5xx6m9/2/
Snippet:
$('.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>
Upvotes: 1
Views: 3433
Reputation: 6304
Because your regex expression is part of a javascript string, any backslashes need to be escaped by using a double backslash. So \d
becomes \\d
.
Also, use the start of string ^
and end of string $
markers to prevent matches from larger strings, such as 01/15/20155
, being successful.
Result:
type: "regExp[/^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\\d\\d$/]",
Snippet:
$('.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>
Upvotes: 4