Created
July 8, 2014 17:48
-
-
Save victorkendy/16257f151740305c96c0 to your computer and use it in GitHub Desktop.
Validação customizada utilizando o Asp.Net MVC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PasswordForteAttribute : ValidationAttribute, IClientValidatable | |
{ | |
private readonly static String PasswordPattern = @"((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{4,100})"; | |
private readonly static Regex PasswordRegex = new Regex(PasswordPattern); | |
public PasswordForteAttribute() : base("Senha muito fraca") { } | |
public override bool IsValid(object value) | |
{ | |
String password = value.ToString(); | |
return PasswordRegex.IsMatch(password); | |
} | |
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) | |
{ | |
// Validaçaõ na view utilizando a regra pronta do Asp.Net MVC | |
var rule = new ModelClientValidationRegexRule(FormatErrorMessage(metadata.DisplayName), PasswordPattern); | |
// Se você precisar de uma validação mais complicada, comentente a linha 17 e descomente as | |
// linhas abaixo: | |
//var rule = new ModelClientValidationRule(); | |
//rule.ErrorMessage = FormatErrorMessage(metadata.DisplayName); | |
//rule.ValidationType = "securepassword"; | |
//rule.ValidationParameters.Add("regex", PasswordPattern); | |
return new List<ModelClientValidationRule>() { rule }; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.validator.unobtrusive.adapters.addSingleVal("securepassword", "regex"); | |
$.validator.addMethod("securepassword", function (value, element, regex) { | |
var passwordRegex = new RegExp(regex); | |
return value.match(passwordRegex); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment