user2083386
user2083386

Reputation: 135

Need to validate the DateTime from server side using form validation in MVC

I have a client side validation which restricts user to enter the date only in a certain range which is 20 years back from now. This is working fine. But the problem is, when the user changes his browser time back to 1 year, then the browser allows to enter the date that is a range greater than 20 years from now. We are using MVC for this. We have 4 tabs where this validation should happen in 2nd form, but the server side call happens when we save all the forms in form and we call the server side in the last tab. How can I achieve this?

I have already added some validation in the server side which restricts the user from server side, but this happens in the last tab when user clicks submit. What I want is, when user clicks on Next button or at least immediately after the user enters the date value in the 2nd tab itself, I want this logic to be happened. The code that I tried is as below:

var enrolledVal = Convert.ToDateTime(model.enrolledValue);
var a = (today.Year * 100 + today.Month) * 100 + today.Day;
var b = (enrolledVal.Year * 100 + enrolledVal.Month) * 100 + enrolledVal.Day;
var enrolledYears = (a - b) / 10000;
if (enrolledYears > 20)
{
var error = new JsonErrorModel { ErrorCode = -1, ErrorMessage = "Enrolled Date Exceeded 20 years"};
return Json(error);
}

Upvotes: 0

Views: 946

Answers (1)

Jake Steffen
Jake Steffen

Reputation: 415

I think this might help

Get the year for enrolled date:

var enrolledVal = Convert.ToDateTime(model.enrolledValue).Year;

Get the current year

var current = DateTime.Now.Year;

Find difference

var result = enrolledVal - current;

Upvotes: 1

Related Questions