7

I need some help with validating a date time string in Javascript, based on the browser's language.

I can get the datetime format easily enough, for instance if the language is set to pt-BR the format would be

dd/MM/yyyy HH:mm:ss

I tried using something like this:

var dateFormat = "dd/MM/yyyy HH:mm:ss";
var x = Date.parseExact($("#theDate").val(), dateFormat);

However x is always Null. I am thinking because Date.parseExact is not able to do times. I need to be able to do this for all browser languages and I would prefer to not use another library. Using Regex is out also since I would need to write so many different expressions.

Does anyone have any suggestions to help me ge on the right track? I am also not against using a webmethod.

I have tried using the following webmethod, which works with en-US but nothing else:

Public Function ValidateDates(ByVal strDate_In As String) As String
    Dim theFormat As String = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern() + " " + CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern()
    Try
        Dim d As DateTime = DateTime.ParseExact(strDate_In, theFormat, CultureInfo.CurrentCulture)
        Return "true"
    Catch ex As Exception
       Return "false"
    End Try
End Function
4
  • 1
    JavaScript doesn't generally understand local dates, so you would have to parse it yourself somehow. How are you getting local date formats to begin with ? Commented May 7, 2015 at 14:38
  • I am using globalize cultures. This is an asp.net web app, and I can also get it with the vb.net cultureinfo. I have to use this dateformat to display the dates in the proper format as well. We use datetimepickers to pick the dates, however we want users to be able to type in dates also, which is where the problem lies. Some countries as dd/mm/yyyy some are dd.mm.yyyy, etc. Part of the problem also lies with the fact that the time is in the same input box. I have tried even using a webmethod that uses vb.net's DateTime.ParseExact but I can't seem to get this to work either. Commented May 7, 2015 at 14:45
  • 1
    So send the date to the server with ajax and parse it into a timestamp there Commented May 7, 2015 at 14:46
  • See my edit for the webmethod that I tried. Commented May 7, 2015 at 14:52

2 Answers 2

1

You can use Regex to do this:

var dateFormat = "dd/MM/yyyy HH:mm:ss";
var x = $("#theDate").val().match(/^(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2}):(\d{2})$/);
console.log(x);

Demo: https://jsfiddle.net/kzzn6ac5/

update The following regex may help you and improve it according to your need:

^((\d{2}|\d{4})[\/|\.|-](\d{2})[\/|\.|-](\d{4}|\d{2}) (\d{2}):(\d{2}):(\d{2}))$

It matches the following format with /.- and yyyy/mm/dd hh:mm:ss or dd/mm/yyyy hh:mm:ss

Updated demo: https://jsfiddle.net/kzzn6ac5/1 or https://regex101.com/r/aT1oL6/1

Further Regex expressions relevant to date matching can be found here.

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

9 Comments

OP said Regex wouldn't be useful for his scenario!
Yeah, I updated the anwser, it matches both dd-mm-yyyy and dd/mm/yyyy. It was tested! :)
@NiteTrip If you want to enforce a particular format you can use the regex to match the general date format and then check what was captured matched by the different capture groups (i.e. "-" or "/") (Assuming that "... should not be able to put it in the format of dd/mm/yyyy." means that you are not allowing certain formats in some contexts)
So what you need is to retrieve date format then set it to: new RegExp(date)
@NiteTrip There is a pretty limited number of date formats. If you check out the link I added to this answer, there is a number of ready-to-use regex for matching of most of the formats. If this is too difficult, just set a format for the user to use. Given that mm-dd-yyyy and dd-mm-yyyy can look the same you will need to set some rules anyway.
|
1

JavaScript date objects are deceptively easy, I worked with them in a project and they had a sneaky learning-curve that takes a lot of time to master (as opposed to the rest of JavaScript, which is relative child's play). I recommend letting VB, or really anything else handle it.

But if you want a way to do it in javascript, without Regex (as stated in your question), you could perform string operations on it like this:

try {
    var user_input = $("#theDate").val();
    var split = user_input.split(" "); // 0: date, 1: time
    var split_time = split[1].split(":"); // 0: hours, 1: minutes, 2: seconds

    d.setHours(split_time[0]);
    d.setMinutes(split_time[1]);
} catch {
    // not in a valid format
}

This solution assumes the input is in the correct format, and if an error occurs, it's not. It's not the best way of doing things, but JS Date objects are seriously horrible.

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.