开发者

ASP MVC 2 Validation : Passing Javascript code to the client

开发者 https://www.devze.com 2023-01-08 16:40 出处:网络
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 Vali

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 开发者_如何学Cam asking here for any idea


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 */
  };
};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号