Reputation: 92
I was wondering if i could get some help on trying to get this page to accept an input, then spit out whether or not it was a valid input or not.
So far I have written this.
<html>
<head>
<title>JavaScript Date Strings</title>
<link rel="stylesheet" href="jsdatestrings.css" />
<script src="http://code.jquery.com/jquery.js"></script>
</head>
<body>
<h1 id="title">JavaScript Popup and Validation</h1>
<img class="popup-btn" src="death.jpg" />
<p>Das Datum (mm/dd/yyyy): <input id = "date" type="text" name="date"></p>
<script>
$(document).ready(function(){
$("input").blur(function(){
var x = $("#date").val();
$("#test").html(x);
});
});
</script>
<p id="test">HERRO!</p>
</body>
</html>
I am not very sure how to get it and work with it. I know the input is working but I need to get something like 09281990 and it should give me something like 09/28/1990 and if I set it to yyyy-mm-dd then it should read it as invalid unless i put 19900928.
Any help would be welcomed. Thank you.
Upvotes: 0
Views: 99
Reputation: 830
$(document).ready(function(){
$("input").blur(function(){
var x = $("#date").val();
var day = x.substring(0,2);
var month = x.substring(2,4);
var year = x.substring(4,8);
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if(!(day+'/'+month+'/'+year).match(re)) {
alert("Invalid date format: " + day+'/'+month+'/'+year);
}else{
$("#test").html(day+'/'+month+'/'+year);
} });
});
Try this..
Upvotes: 1
Reputation: 3027
You can use moment.js library: http://momentjs.com/ It knows how to parse dates from lots of different formats.
And it also has a method moment(date).isValid() which shows you if the object you are passing was successfully parsed to date.
moment("12-25-1995", "MM-DD-YYYY") // will parse your date from MM-DD-YYYY format;
moment("not a real date").isValid(); // false
Upvotes: 1