globetrotter
globetrotter

Reputation: 1047

ASP.NET Core data annotation - different values between two properties

I have this viewmodel:

public class VM
{
    [Required]
    public int Int1 { get; set; }
    [Required]
    public int Int2 { get; set; }
}

In the view, these two ints are chosen via dropdowns. I would like the unobtrusive validation to fail if the same value is selected from both dropdowns (e.g. assume Int1 and Int2 can take values ranging 1-10 and the user chooses 9 for both, validation should fail). I am looking to achieve this with data annotations instead of writing Javascript in the frontend.

I can't find a built-in validation attribute, I found [Compare(string otherProperty)] but I am essentially looking for the negation of Compare.

Upvotes: 0

Views: 500

Answers (1)

Edward
Edward

Reputation: 29976

You need to implement your own logic.

  1. Remote validation Controller

    public class NotEqualController : Controller
    {
            [AcceptVerbs("Get", "Post")]
            public IActionResult Verify()
            {
            string firstKey = Request.Query.Keys.ElementAt(0);
            string secondKey = Request.Query.Keys.ElementAt(1);
            string first = Request.Query[firstKey];
            string second = Request.Query[secondKey];
            if (string.Equals(first, second))
            {
                    return Json(false);
                    //return Json(data: $"Values for these two fields should not be same.");
            }
            return Json(data: true);
            }
    }
    
  2. Model Configuration

    public class Product
    {
            public int Id { get; set; }
            [Remote(action: "Verify", controller: "NotEqual", AdditionalFields = nameof(UserImage), ErrorMessage = "Are Same")]
            public string Name { get; set; }
            [Remote(action: "Verify", controller: "NotEqual", AdditionalFields = nameof(Name), ErrorMessage = "Are Same")]
            public string UserImage { get; set; }
    }
    

    Since you may use this logic for many different model and fields, I implement the logic to use the fields from querystring instead of Verify method parameter.

Upvotes: 1

Related Questions