Reputation: 9986
I want to use JavaScript to do some client-side validation to check whether a string matches the regex:
Whath is wrong in my js ..?
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Test</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "30/12/2015";
var patt = new RegExp("DD/MM/YYYY");
var res = patt.test(str);
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
Upvotes: 0
Views: 117
Reputation: 444
Regex to just check the format of the input string:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Test</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "11/12/2015";
document.getElementById("demo").innerHTML = testDateFormat(str);
}
function testDateFormat(str) {
return (str.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/)) ? true : false;
}
</script>
</body>
</html>
Upvotes: 1
Reputation: 2824
It is not a regular expression. The easiest (but rather naive) solution would be:
var isDateCorrect = new Date(str).toString() !== "Invalid Date";
new Date(str)
will try to parse the date and if it fails, it'll return the object that after calling toString
on it produces a string Invalid Date
, so you've got kind of a native date validation.
Upvotes: 3
Reputation: 7771
DD/MM/YYYY
is not a valid RegEx. Use \d\d\/\d\d\/\d\d\d\d
instead:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Test</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "30/12/2015";
var patt = new RegExp("\d\d\/\d\d\/\d\d\d\d");
var res = patt.test(str);
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
Upvotes: 0