0

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 and is not a invalid value like "2231" or "afaf".

2 Answers 2

1

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.

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

3 Comments

Also validate on the client to stop a real user from wasting a server round trip
@mplungjan Yes, as a usability enhancement. But not in the case of a jQuery plugin that provides the widget to enter the data. In that case the widget should prevent the user from accidentally entering invalid information.
Oswald, Ah, missed that part. Yes. If the user manages to enter crap in a widget, then it is surely maliciously and cannot be tested on the client. At least my first comment was also to test on the server :)
0

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.

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.