0

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 ..?

PLUNKER

<!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>
Mercer
  • 9,736
  • 30
  • 105
  • 170
  • You have to use a regular expression to achieve that. You can take a look at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions. If you want to parse the date, some libraries could be useful (moment.js). – andrusieczko Jan 22 '15 at 16:03
  • That's a date format, not a regular expression. You may need to do a bit of background reading on what a regular expression is. – Adrian Wragg Jan 22 '15 at 16:03
  • i want just to test the string not the date – Mercer Jan 22 '15 at 16:05

3 Answers3

3

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.

andrusieczko
  • 2,824
  • 12
  • 23
1

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>
Linus
  • 448
  • 2
  • 5
0

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>
Ian Hazzard
  • 7,661
  • 7
  • 34
  • 60