0

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.

2 Answers 2

1
     $(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..  
Sign up to request clarification or add additional context in comments.

4 Comments

I tried it out and it works but I don't want to just settle for, it works thank you, I want to see if I could get a bit of an explanation so that way I understand it and I don't waste people's time just asking dumb questions.
Have a look Regular Expression tutorial regular-expressions.info/tutorial.html
For now I seem to have the program working but one thing I wanted to do now is to give the user the option to chose formats like if I don't like the one you gave me, I can change it to yyyy/mm/dd. I would like to give it a whack on my own but what would you recommend? Switch statement? If else? etc....
Give d user a listbox option where he can select d format based on d format selected u sub-string the text box value...
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.