ASP.NET MVC Custom Client-side Model Validation (compare two int values) with ivalidatableobject

608 views Asked by At

I have custom validation comparing two values in my model. The server-side validation is functioning correctly.

However, I'm wondering what I need to add to get the custom model validation to work client-side (i.e. show the little red error messages before the submit button is pressed). Right now my little red error message only appears after the submit button is pressed.

A simplified version of the relevant code is included below:

In the viewmodel.cs file:

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Collections.Generic;
public class MyViewModel : IValidatableObject
{
    public int value1 { get; set; }

    [Range(0, 1000, ErrorMessage = "Must be a positive integer between 0 and 1000")]      
    public int value2 { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (value2 > value1)
            yield return new ValidationResult("value2 cannot be more than value1).", new List<string> { "value1" });

    }
}

In the cshtml view:

<input asp-for="value1" />
<p style="color:red"><span asp-validation-for="value1"></span> </p>
<input asp-for="value2" />
<p style="color:red"><span asp-validation-for="value2"></span> </p>

I check the 'ModelState.IsValid' inside the controller when the form is posted.

'jquery.validate.min.js' and 'jquery.validate.unobtrusive.min.js' are included (and the client-side range validation works correctly, so I know that the jquery libraries are set up properly).

0

There are 0 answers