Good afternoon guys,
Next, I need to validate if one of two fields is filled, I tried to create an Attribute function with ValidationAttribute but it did not validate correctly, I think jQuery.validate does not recognize it.
Follow the codes:
Class ValidationAttribute
public class VerifyPhoneAttribute : ValidationAttribute, IClientValidatable
{
private readonly string OtherPropertyName;
public VerifyPhoneAttribute(string otherPropertyName)
: base("Um dos telefones deve estar preenchido.")
{
OtherPropertyName = otherPropertyName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var otherPropertyInfo = validationContext.ObjectType.GetProperty(OtherPropertyName);
string otherPhone = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null).ToString(), thisDate = value.ToString();
if (string.IsNullOrEmpty(otherPhone) && string.IsNullOrEmpty(thisDate))
return new ValidationResult("Um dos telefones deve estar preenchido.");
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRegexRule(FormatErrorMessage(metadata.DisplayName), OtherPropertyName);
return new List<ModelClientValidationRule>() { rule };
}
}
Model
[MaxLength(15)]
[Display(Name = "Primeiro telefone")]
[VerifyPhone("client_phone2")]
public string client_phone1 { get; set; }
[MaxLength(15)]
[Display(Name = "Segundo telefone")]
public string client_phone2 { get; set; }
View
<div class="col-md-2">
@Html.LabelFor(model => model.client_phone1)
@Html.EditorFor(model => model.client_phone1, new { htmlAttributes = new { @class = "form-control input-sm input-phone input-phone1" } })
@Html.ValidationMessageFor(model => model.client_phone1, "", new { @class = "text-danger" })
</div>
<div class="col-md-2">
@Html.LabelFor(model => model.client_phone2)
@Html.EditorFor(model => model.client_phone2, new { htmlAttributes = new { @class = "form-control input-sm input-phone input-phone2" } })
@Html.ValidationMessageFor(model => model.client_phone2, "", new { @class = "text-danger" })
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script>
$.validator.unobtrusive.adapters.addSingleVal("VerifyPhone", "phone2");
$.validator.addMethod("VerifyPhone", function (value, element, phone2) {
return value.match(phone2);
});
</script>
}