title: client-side validation in custom validation attribute - asp.net mvc 4
body: <p>I have followed some articles and tutorials over the internet in order to create a custom validation attribute that also supports client-side validation in an asp.net mvc 4 website. This is what i have until now:</p>
  
  <p><strong>RequiredIfAttribute.cs</strong></p>
  
  <pre><code>[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] //Added
  public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
  {
      private readonly string condition;
      private string propertyName; //Added
  
      public RequiredIfAttribute(string condition)
      {
          this.condition = condition;
          this.propertyName = propertyName; //Added
      }
  
      protected override ValidationResult IsValid(object value, ValidationContext validationContext)
      {
          PropertyInfo propertyInfo = validationContext.ObjectType.GetProperty(this.propertyName); //Added
          Delegate conditionFunction = CreateExpression(validationContext.ObjectType, _condition);
          bool conditionMet = (bool)conditionFunction.DynamicInvoke(validationContext.ObjectInstance);
  
          if (conditionMet)
          {
              if (value == null)
              {
                  return new ValidationResult(FormatErrorMessage(null));
              }
          }
  
          return ValidationResult.Success;
      }
  
      private Delegate CreateExpression(Type objectType, string expression)
      {
          LambdaExpression lambdaExpression = System.Linq.Dynamic.DynamicExpression.ParseLambda(objectType, typeof(bool), expression); //Added
          Delegate function = lambdaExpression.Compile();
          return function;
      }
  
      public IEnumerable&lt;ModelClientValidationRule&gt; GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
      {
          var modelClientValidationRule = new ModelClientValidationRule
          {
              ValidationType = "requiredif",
              ErrorMessage = ErrorMessage //Added
          };
  
          modelClientValidationRule.ValidationParameters.Add("param", this.propertyName); //Added
          return new List&lt;ModelClientValidationRule&gt; { modelClientValidationRule };
      }
  }
  </code></pre>
  
  <p>Then i applied this attribute in a property of a class like this</p>
  
  <pre><code>[RequiredIf("InAppPurchase == true", "InAppPurchase", ErrorMessage = "Please enter an in app purchase promotional price")] //Added "InAppPurchase"
  public string InAppPurchasePromotionalPrice { get; set; }
  
  public bool InAppPurchase { get; set; }
  </code></pre>
  
  <p>So what i want to do is display an error message that field InAppPurchasePromotionalPrice is required when InAppPurchase field is true (that means checked in the form). The following is the relevant code form the view:</p>
  
  <pre><code>&lt;div class="control-group"&gt;
                  &lt;label class="control-label" for="InAppPurchase"&gt;Does your app include In App Purchase?&lt;/label&gt;
                  &lt;div class="controls"&gt;
                      @Html.CheckBoxFor(o =&gt; o.InAppPurchase)
                      @Html.LabelFor(o =&gt; o.InAppPurchase, "Yes")
                  &lt;/div&gt;
              &lt;/div&gt;
              &lt;div class="control-group" id="InAppPurchasePromotionalPriceDiv" @(Model.InAppPurchase == true ? Html.Raw("style='display: block;'") : Html.Raw("style='display: none;'"))&gt;
                  &lt;label class="control-label" for="InAppPurchasePromotionalPrice"&gt;App Friday Promotional Price for In App Purchase: &lt;/label&gt;
                  &lt;div class="controls"&gt;
                      @Html.TextBoxFor(o =&gt; o.InAppPurchasePromotionalPrice, new { title = "This should be at the lowest price tier of free or $.99, just for your App Friday date." })
                      &lt;span class="help-inline"&gt;
                          @Html.ValidationMessageFor(o =&gt; o.InAppPurchasePromotionalPrice)
                      &lt;/span&gt;
                  &lt;/div&gt;
              &lt;/div&gt;
  </code></pre>
  
  <p>This code works perfectly but when i submit the form a full post is requested on the server in order to display the message. So i created JavaScript code to enable client-side validation:</p>
  
  <p><strong>requiredif.js</strong></p>
  
  <pre><code>(function ($) {
      $.validator.addMethod('requiredif', function (value, element, params) {
          /*var inAppPurchase = $('#InAppPurchase').is(':checked');
  
          if (inAppPurchase) {
              return true;
          }
  
          return false;*/
  
          var isChecked = $(param).is(':checked');
  
          if (isChecked) {
              return false;
          }
  
          return true;
      }, '');
  
      $.validator.unobtrusive.adapters.add('requiredif', ['param'], function (options) {
          options.rules["requiredif"] = '#' + options.params.param;
          options.messages['requiredif'] = options.message;
      });
  })(jQuery);
  </code></pre>
  
  <p>This is the proposed way in msdn and tutorials i have found</p>
  
  <p>Of course i have also inserted the needed scripts in the form:</p>
  
  <ol>
  <li>jquery.unobtrusive-ajax.min.js</li>
  <li>jquery.validate.min.js</li>
  <li>jquery.validate.unobtrusive.min.js</li>
  <li>requiredif.js</li>
  </ol>
  
  <p>BUT...client side validation still does not work. So could you please help me find what am i missing? Thanks in advance.</p>