I have inherited a project, where there the form has several section as well as several models. One section/model has: Name, Address, BirthDate (DOB), etc. A user can fill that out, then click the "Add" button to add another member of the family. The fields, after clicking "Add" are identical in appearance. It also uses the same model (why not!). This currently works fine!
The issue #1, no validation of the input date, so a user could enter 13/12/8500 (mm/dd/yyyy), so naturally I had to add a validation on the BirthDate (DOB) field. #1 somewhat solved:
** Code Model
[DataType(DataType.DateTime, ErrorMessage = "Invalid Date")]
[Display(Name = "Birth Date (mm/dd/yyyy format):")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
[Remote("IsValidDateOfBirth", "AML", HttpMethod = "POST", ErrorMessage = "Please provide a valid date of birth.")]
public DateTime? DOB { get; set; }
** Code Controller
[HttpPost]
public JsonResult IsValidDateOfBirth([Bind(Prefix = "setlList[0].DOB")]string DOB)
{
var min = DateTime.Now.AddYears(-200);
var max = DateTime.Now;
var msg = string.Format("Please enter a value between {0:MM/dd/yyyy} and {1:MM/dd/yyyy}", min, max);
try
{
var date = DateTime.Parse(DOB);
if (date > max)
return Json(string.Format("Date can't be greater than {0:MM/dd/yyyy}", max));
else if (date < min)
return Json(string.Format("Date should be greater than {0:MM/dd/yyyy}", min));
else
return Json(true);
}
catch (Exception)
{
return Json(msg);
}
}
The above implementation works fine for the first/initial BirthDate! Yeah baby!
I hit the "Add" to add another member, so far so good, but when I put in a Birthday - Bamm Issue #2 occurs. The IsValidDateOfBirth IS called for the 2nd BirthDate but a null is passed to the validator.
I believe it has to do with the binding in the validator (([Bind(Prefix = "setlList[0].DOB")]), I tried to remove the binding, but that didn't work (null was being passed 100% of the time). I tried to shorten to Prefix=setList, surprise - that didn't work either.
I keep scratching my head on HOW to accomplish this. I thought of having multiple validator methods (which seem very silly) but this wouldn't work; due to using the same Model (not need to create multiple models either).
I must be missing something here??
Yes, using jQuery 2.1.4, jQuery Validation Plugin 1.11.1, and jQuery unobtrusive