Mercer
Mercer

Reputation: 9986

Check a String matches a Regex

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>

Upvotes: 0

Views: 117

Answers (3)

Linus
Linus

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

andrusieczko
andrusieczko

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

Ian Hazzard
Ian Hazzard

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

Related Questions