0

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).

Taraz
  • 1,242
  • 13
  • 13
  • In order to get client side validation, you must apply create a `ValidationAttribute` which implement `IClientValidatable` (and write add the scripts to the `$.validator`) –  Sep 05 '18 at 22:38
  • You can use a plugin such as [foolproof](https://github.com/leniel/foolproof) or if you want to write your own, refer [The Complete Guide To Validation In ASP.NET MVC 3 - Part 2](https://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2) –  Sep 05 '18 at 22:39
  • 1
    Note your view code suggests you are using asp.net-core-mvc, (I have re-tagged it) so you need to implement `IClientModelValidator`, not `IClientValidatable` - refer [Model validation in ASP.NET Core MVC](https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.1) –  Sep 05 '18 at 22:42

0 Answers0