I am trying to implement unobtrusive client validation for the first time. I feel like I am extremely close, just cannot get the message to display on the screen. If someone can guide me in the correct direction here I would appreciate it. Here is what I have so far.
Validation Attribute
public class WellTestRecordVal : ValidationAttribute , IClientValidatable
{
private WellTestViewModel record;
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
record = (WellTestViewModel) validationContext.ObjectInstance;
if (record.WtStartTime > record.WtEndtime)
return new ValidationResult("This is my server val message.");
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var startDate = DateTime.Today;
var rule1 = new ModelClientValidationRule();
rule1.ValidationType = "startdaterule";
rule1.ErrorMessage = "this is my iclient val message.";
return new[] {rule1};
}
I have it applied to to the property on my model as such:
[WellTestRecordVal]
[DataType(DataType.DateTime)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-ddThh:mm:ss}")]
public DateTime WtStartTime { get; set; }
In my bundles I have all the unobtrusive.js and validate.unobtrusive.js files I should need.
My view has the validation on the element.
<label>
<span>Start Date</span>
@Html.TextBoxFor(x => x.WtStartTime, "{0:yyyy-MM-ddThh:mm:ss}", new { @class = "form-control", @type = "datetime-local", id = "startDate" })
@Html.ValidationMessageFor(m => m.WtStartTime)
</label>
My Jquery for the view is as such.
<script type="text/javascript">
$.validator.addMethod("startdaterule",
function(value, element, params) {
var endDate = $("#endDate").val();
if (value > endDate) {
return false;
}
return true;
});
$.validator.unobtrusive.adapters.add("startdaterule",function(options) {
options.rules["startdaterule"] = {};
options.messages["startdaterule"] = options.message;
});
I am using an Ajax.BeginForm on the view.
I can see that the message in my GetClientValidationRules is getting to the view when I inspect it.
What am I missing to get this to display in the view itself? I feel like I am missing some extremely simple that I might have overlooked on the several resources I have reviewed on this.
This is a different approach, but for conditional validation I recommend using foolproof validation.
To do this you need to:
mvcfoolproof.unobtrusive.jsto your scripts (get it from here)Then you can use conditional validation like this:
That's it, you don't need to write your own JavaScript code for client side validation. Just note that you need ValidationSummary added to your view. You need to add the following line to your view, and it would display the error messages.