views:

24

answers:

1

I am writing a custom validation attribute It does conditional validation between two fields When I create my rule, one of the things that I could not solve is how to pass javascript code through ValidationParameters

Usually, I just do ValidationParameters["Param1"] = "{ required :function(element) { return $("#age").val() < 13;) }"

However, the MicrosoftMvcJQueryValidation.js routines trnasforms this to

Param1 = "{ required :function(element) { return $("#age").val() < 13;) }"

I could use Param1.eval() in Javascript. This will evaluates and executes the code but I just want to evalute the code and execute it later

JSON parser does not parse string contening Javascript code

So I am asking here for any idea

A: 

Not sure how you would inject javascript as you describe, but you may want to consider using the custom validation pattern for ASP.NET MVC 2.

Important pieces are the ValidationAttribute, DataAnnotationsModelValidator, registering the validator in Application_Start with DataAnnotationsModelValidatorProvider.RegisterAdapter, and the client side Sys.Mvc.ValidatorRegistry.validators function collection to register your client side validation code.

Here's the example code from my post.

[RegularExpression("[\\S]{6,}", ErrorMessage = "Must be at least 6 characters.")]
public string Password { get; set; }


[StringLength(128, ErrorMessage = "Must be under 128 characters.")]
[MinStringLength(3, ErrorMessage = "Must be at least 3 characters.")]
public string PasswordAnswer { get; set; }


public class MinStringLengthAttribute : ValidationAttribute
{
  public int MinLength { get; set; }

  public MinStringLengthAttribute(int minLength)
  {
    MinLength = minLength;
  }

  public override bool IsValid(object value)
  {
    if (null == value) return true;     //not a required validator
    var len = value.ToString().Length;
    if (len < MinLength)
      return false;
    else
      return true;
  }
}

public class MinStringLengthValidator : DataAnnotationsModelValidator<MinStringLengthAttribute>
{
  int minLength;
  string message;

  public MinStringLengthValidator(ModelMetadata metadata, ControllerContext context, MinStringLengthAttribute attribute)
    : base(metadata, context, attribute)
  {
    minLength = attribute.MinLength;
    message = attribute.ErrorMessage;
  }

  public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
  {
    var rule = new ModelClientValidationRule
    {
      ErrorMessage = message,
      ValidationType = "minlen"
    };
    rule.ValidationParameters.Add("min", minLength);
    return new[] { rule };
  }
}


protected void Application_Start()
{
  RegisterRoutes(RouteTable.Routes);
  DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MinStringLengthAttribute), typeof(MinStringLengthValidator));
}


Sys.Mvc.ValidatorRegistry.validators["minlen"] = function(rule) {
  //initialization
  var minLen = rule.ValidationParameters["min"];

  //return validator function
  return function(value, context) {
    if (value.length < minLen) 
      return rule.ErrorMessage;
    else
      return true;  /* success */
  };
};
Tyler Jensen
I should note that this code resolved a specific issue in MVC 2 on .NET 3.5. It's no longer needed in .NET 4.0 since they added the min length attribute into the component library classes. Still, this gives you a good example of how to hook up custom client side validation to extend standard MVC 2 client side validators.
Tyler Jensen
Thank for your commentsHowever, the main issue is how to pass Javascript code not how to do custom validationVery often, you need to pass Javascript code in such Validation routines
Understood. I think that the only way you can "inject" javascript code, because of the nature of the browser, is to emit the javascript as part of your HTML output. You may be able to write a <script> to the DOM and then call the function declared in the DOM, but I've never tried that.
Tyler Jensen