Asp.net MVC Custom Client Validation not displaying on screen

129 Views Asked by At

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.

2

There are 2 best solutions below

1
Hooman Bahreini On

This is a different approach, but for conditional validation I recommend using foolproof validation.

To do this you need to:

  1. install follproof nuget package
  2. add mvcfoolproof.unobtrusive.js to your scripts (get it from here)

Then you can use conditional validation like this:

public class MyModel 
{
    public DateTime WtStartTime { get; set; } 

    /* I want end time to be greater than or equal to start time */
    [GreaterThanOrEqualTo("WtStartTime", ErrorMessage="End should be >= Start")]
    public DateTime WtEndtime{ get; set; } 

}

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.

@Html.ValidationSummary(true, "", new { @class = "text-danger" })
0
GlitchEclipse On

I was able to narrow down my issue after purchasing the book. Professional ASP.NET MVC 5. My syntax was extremely close. I had two issues. One, I passed no parameter to check my value against. Second, I needed to call @Scripts.Render("~/bundles/jqueryval") before my validation script that I render. It wasn't good enough to just include it. The order matters.