2

I have a reservation page where someone would enter the date for it and I need to validate it, but i am not sure how to do this in javascript here is the html code

   <input type="text" name="date" />

now i have seend a few examples but not clear enough, the entry in the textbox should be something like 11/07/2011 3:45 AM.I would appreciate any help or advise on how to achieve this with javascript.

3

2 Answers 2

2

Why do you let him Type chars ?

give him some dateTime Picker.

http://plugins.jquery.com/project/DateTimepicker

Sign up to request clarification or add additional context in comments.

Comments

2

if not using jQuery

 var errormessage = "";
 function checkIsValidDateTime(){
      errormessage = "";
      var isvalid = false;
      var dt = document.getElementsByName("date")[0].value;
      var parts = dt.split(" ");
      if(parts.length == 3){
         var date = parts[0];
         var time = parts[1];
         var ampm = parts[2];
         if(ampm.length == 2 && (ampm.toLowerCase() == "am" || ampm.toLowerCase() == "pm")){
            var validformatdate=/^\d{2}\/\d{2}\/\d{4}$/;
            if (validformatdate.test(date)){
                var validformattime = /^\d{1,2}:\d{2}$/;
                if (validformattime.test(date)){
                     isvalid = true;
                }else{errormessage = "Time is not in the format HH:MM";}
            }else{errormessage = "Date is not in the format dd/mm/yyyy";}
         }else{errormessage = "DateTime does not have AM/PM at the end";}
      }else{errormessage = "DateTime is not in the format 11/07/2011 3:45 AM";}
      return isvalid;
 }

Then when the submit button is clicked set the onclick event to call that function and you can even display the error message if it is not empty. If the function returns true then process normally ortherwise stop the submit.

1 Comment

for the date I made the assumption in the validformatdate check that the day was going to be 02/11/2011 if less than 10 but it can be rewritten to /^\d{1,2}\/\d{2}\/\d{4}$/ if that is not the case

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.