views:

679

answers:

2

I've been looking at the file MicrosoftMvcJQueryValidation.js which is the layer between your page and the jquery.validate object in ASP.NET MVC 2 Beta.

It will allow any type of validation rule supported by jquery.validate and had additional special handling for regularexpressions, strings, ranges and required fields. If it is a generic/unknown rule type it will just pass through the parameters like this :

  default:
     __MVC_ApplyValidator_Unknown(rulesObj,
         thisRule.ValidationType, thisRule.ValidationParameters);
    break;

However - I cannot seem to figure out how to inject additional rules into the JSON that is generated by the framework, such as 'email'. Normally the rules just come from the attributes such as [Required].

I know there are lots of extensivbility points to replace the whole validation metadata provider - but I'm looking for a simple way.

How can I use - for instance the 'email' or 'creditcard' validators in conjunction with a simple model like this:

public class LoginDetails { public bool Editable { get; set; }

    [Required(ErrorMessage="Please enter your email")]
    public string Username { get; set; }

    [Required(ErrorMessage="Please enter your password")]
    public string Password { get; set; }
}
+2  A: 

For different types of data you can keep the Required message but also add different attributes below them. For Email and Credit Car a Regular Expression like this would probably work best.

[Required(ErrorMessage="Please enter your email")]
[RegularExpression(@"\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b", 
  ErrorMessage="Please enter a valid email address.")]
public string Email { get; set; }

[Required(ErrorMessage="Please enter your password")]
[RegularExpression(@"^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$.", 
  ErrorMessage="Please enter a valid Credit Card.")]
public string CreditCard { get; set; }

Check out this, this and this link for more info.

Victor
wasnt especially impressed AT ALL with jquery.validate's credit card validation (see http://stackoverflow.com/questions/1864208). i may just do an onblur do it manually. this is probably a good solution for email though
Simon_Weaver
+2  A: 

Use a DataAnnotationsModelValidator

Like this.

Use these includes

/Scripts/jquery-1.3.2.js

/Scripts/jquery.validate.js

/Scripts/MicrosoftMvcJQueryValidation.js

Use a validation function

    <script type="text/javascript">
    $.validator.addMethod("price", function(value, element, paras) {
        if (value.length == 0) {
            return true;
        }
        if (value > paras.minValue) {
            var cents = value - Math.floor(value);
            if (cents >= 0.99 && cents < 0.995) {
                return true;
            }
        }
        return false;
    });
</script>
djeeg