ASP.NET MVC – How to Check if User’s Form Submission Answer is Unique

asp.net-mvcc

So, I have a form that has security questions and textfields for the user to type in their answer. I want to prevent the user from typing in the same answer to every security question selected. So I am wondering, if there is a .NET attribute I can use to do validation on client side or server side approach that would prevent duplicate answer submission. Every answer that the user types in has to be unique.

So, How can I check if answer the user typed in is unique in the form submission?

I am using ASP.NET MVC 4

Best Answer

Your best bet is probably having a custom validation component built for this purpose. It is reusable once implemented and follows the pattern of validators used for MVC4.

Adding Custom Validator for MVC4

To check for the uniqueness:

In C#:

  1. Get all the input values in the text boxes into a collection.
  2. Check if the length of unique values is the same as length of the collection: bool cintainsDuplicates = items.Distinct().Count() != items.Length;

In Javascript in case you choose to build custom validator:

  1. Same, get all the values in a collection, probably by class that will be assigned to all boxes of that type.
  2. Use one of the suggested solutions here to check for duplicates: Google Search Results