title: Custom client side validation attribute with parameter in ASP.NET Core using IClientModelValidator
body: <p>I'm attempting to create my own client side validation attribute that would validate the property of a form on submit. I have been referencing the following Microsoft document: <a href="https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.1#custom-validation" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.1#custom-validation</a>.</p>
  
  <p>I am unsure on how to add the validation rule to jQuery's validator object. This is how far I have gotten:</p>
  
  <p>My ValidationAttribute is as follows</p>
  
  <pre><code>public class CannotEqualValue : ValidationAttribute, IClientModelValidator
  {
      private readonly string _value;
  
      public CannotEqualValue(string value)
      {
          _value = value;
      }
  
      public void AddValidation(ClientModelValidationContext context)
      {
          if (context == null)
              throw new ArgumentNullException(nameof(context));
  
          MergeAttribute(context.Attributes, "data-val", "true");
          MergeAttribute(
              context.Attributes, "data-val-cannotbevalue", GetErrorMessage()); //???
          MergeAttribute(
              context.Attributes, "data-val-cannotbevalue-value", _value);      //???
      }
  
      protected override ValidationResult IsValid(
          object value, 
          ValidationContext validationContext)
      {
          var category = (Category) validationContext.ObjectInstance;
  
          if (category.Name == _value)
              return new ValidationResult(GetErrorMessage());
  
          return ValidationResult.Success;
      }
  
      private bool MergeAttribute(
          IDictionary&lt;string, string&gt; attributes, 
          string key, 
          string value)
      {
          if (attributes.ContainsKey(key)) return false;
  
          attributes.Add(key, value);
          return true;
      }
  
      private string GetErrorMessage()
      {
          return $"Name cannot be {_value}.";
      }
  }
  </code></pre>
  
  <p>The ValidationAttribute is used in a model like so</p>
  
  <pre><code>public class Category
  {
      [Key]
      public int Id { get; set; }
  
      [Required(ErrorMessage = "Name is required and must not be empty.")]
      [StringLength(200, ErrorMessage = "Name must not exceed 200 characters.")]
      [CannotEqualValue("Red")]
      public string Name { get; set; }
  }
  </code></pre>
  
  <p>I am referencing both jQuery validation and unobtrusive in my page.</p>
  
  <p>I am unsure on how to add the rule to jQuery's validator object:</p>
  
  <pre><code>$.validator.addMethod("cannotbevalue",
      function(value, element, parameters) {
          //???
      });
  
  $.validator.unobtrusive.adapters.add("cannotbevalue",
      [],
      function(options) {
          //???
      });
  </code></pre>