수색…


소개

mvc.net은 모델 검증을위한 데이터 주석을 소개합니다. 이것은 Xamarin에서도 가능합니다.

간단한 예

너겟 패키지 System.ComponentModel.Annotations 추가

클래스 정의 :

public class BankAccount  
{  

   public enum AccountType  
   {  
       Saving,  
       Current  
   }  

   [Required(ErrorMessage="First Name Required")]  
   [MaxLength(15,ErrorMessage="First Name should not more than 1`5 character")]  
   [MinLength(3,ErrorMessage="First Name should be more than 3 character")]  
   public string AccountHolderFirstName { get; set; }  

   [Required(ErrorMessage="Last Name Required")]  
   [MaxLength(15,ErrorMessage="Last Name should not more than 1`5 character")]  
   [MinLength(3,ErrorMessage="Last Name should be more than 3 character")]  
   public string AccountHolderLastName { get; set; }  

   [Required]  
   [RegularExpression("^[0-9]+$", ErrorMessage = "Only Number allowed in AccountNumber")]  
   public string AccountNumber { get; set; }  

   public AccountType AcType { get; set; }  
}

유효성 검사기 정의 :

public class GenericValidator   
{  
    public static bool TryValidate(object obj, out ICollection<ValidationResult> results)  
    {  
        var context = new ValidationContext(obj, serviceProvider: null, items: null);  
        results = new List<ValidationResult>();  
        return Validator.TryValidateObject(  
            obj, context, results,  
            validateAllProperties: true  
        );  
    }  
}

validator를 사용합니다 :

var bankAccount = new BankAccount();  
ICollection<ValidationResult> lstvalidationResult;  

bool valid = GenericValidator.TryValidate(bankAccount, out lstvalidationResult);  
if (!valid)  
{  
    foreach (ValidationResult res in lstvalidationResult)  
    {  
        Console.WriteLine(res.MemberNames +":"+ res.ErrorMessage);  
    }  
      
}  
Console.ReadLine();

생성 된 출력 :

First Name Required
Last Name Required
The AccountNumber field is required.


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow