DataAnnotation to compare two properties

时间秒杀一切 提交于 2019-11-28 22:22:19

问题


Is there any way of using data annotations to compare two form field (eg. to confirm an email address) are the same, before allowing the form to be posted?

eg. can the regular expression data annotation use the match function to reference another property in a ViewModel?


回答1:


Use the CompareAttribute

public string EmailAddress {get; set;}

[Compare(nameof(EmailAddress), ErrorMessage = "Emails mismatch")]
public string VerifiedEmailAddress { get; set; }



回答2:


As one possibe option self-validation:

Implement an interface IValidatableObject with method Validate, where you can put your validation code.

public class TestModel : IValidatableObject
{
    public string Email{ get; set; }
    public string ConfirmEmail { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (Email != ConfirmEmail)
        {
            yield return new ValidationResult("Emails mismatch", new [] { "ConfirmEmail" });
        }
    }
}

Please notice: this is only server-side validation.



来源:https://stackoverflow.com/questions/21931103/dataannotation-to-compare-two-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!