Skip to content

Instantly share code, notes, and snippets.

@victorkendy
Created July 8, 2014 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save victorkendy/16257f151740305c96c0 to your computer and use it in GitHub Desktop.
Save victorkendy/16257f151740305c96c0 to your computer and use it in GitHub Desktop.
Validação customizada utilizando o Asp.Net MVC
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 };
}
}
$.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