开发者

How do i validate a datetime field input through javascript?

开发者 https://www.devze.com 2023-03-02 18:53 出处:网络
I have an HTML page that has several fields and one of them is to select DateTime using jquery plugin, which lets user to select DateTime like : 2011-06-05 07:10 or 2011-03-05 11:10 etc.My problem is

I have an HTML page that has several fields and one of them is to select DateTime using jquery plugin, which lets user to select DateTime like : 2011-06-05 07:10 or 2011-03-05 11:10 etc.My problem is how do I validate this field value before posting it to server.I want to use javascript to ensure that the field value is only DateTime in this format an开发者_JAVA百科d is not a invalid value like "2231" or "afaf".


If the user wants to tamper with the data he sends, he does so by circumventing the jQuery plugin as well as any additional code for validation on the client. Then it makes no sense to write additional code for validation on the client.

If the user does not want to tamper with the data he sends, the jQuery plugin alone should ensure an appropriate format. Then it makes no sense to write additional code for validation on the client.

Validate this field on the server only.


You MUST validate on the server too.

The simplest way on the client to test a date string like that is to use Date.parse like this (I am not testing the format other than using date parse. If the user enters another format, you will need to test that too)

var DT = Date.parse(DateTime.replace("-","/","g"));
if (isNaN(DT)) {
  alert('Invalid date');
  return false;
}
var testDate = new Date(DT);
var parts = DateTime.split(" ")[0].split("-");
if (testDate.getFullYear() != parseInt(parts[0]) ||
    testDate.getMonth() != parseInt(parts[1]-1) ||
    testDate.getDate() != parseInt(parts[2])) {
  alert('Invalid date');
  return false;
}

This is of course completely unnecessary if you use a widget to create the date.

0

精彩评论

暂无评论...
验证码 换一张
取 消