6

유효성 검사 SSN을 사용하여 재사용 성을 향상시키기 위해 RegularExpressionAttribute을 상속하려고합니다.RegularExpressionAttribute를 상속하려고하는데 더 이상 유효성을 검사하지 않습니다.

public class FooModel 
{ 
    [RegularExpression(@"^(?!000)(?!666)(?!9[0-9][0-9])\d{3}[- ]?(?!00)\d{2}[- ]?(?!0000)\d{4}$", ErrorMessage = "The SSN you entered is invalid. If you do not have this number please leave the field blank")] 
    public string Ssn { get; set; } 
} 

클라이언트와 서버에 올바르게 유효성을 검사합니다 :

나는 다음과 같은 모델을 가지고있다.

public class SsnAttribute : RegularExpressionAttribute 
{ 
    public SsnAttribute() : base(@"^(?!000)(?!666)(?!9[0-9][0-9])\d{3}[- ]?(?!00)\d{2}[- ]?(?!0000)\d{4}$") 
    { 
     ErrorMessage = "SSN is invalid"; 
    } 
} 

그럼 내가 변경 내는 FooModel과 같이 :

public class FooModel 
{ 
    [Ssn(ErrorMessage = "The SSN you entered is invalid. If you do not have this number please leave the field blank")] 
    public string Ssn { get; set; } 
} 

이제 눈에 거슬리지 데이터를 렌더링하지 않습니다 유효성 검사에 속성 그래서 같은 속성 자체 검증에 그 긴 정규 표현식을 캡슐화하고 싶어 클라이언트. 나는 이것이 왜 본질적으로 똑같은 것처럼 보이기 때문에, 왜 그런지 확실히 모르겠습니다.

제안 사항? 에서

답변

13

당신의 Application_Start 속성을 클라이언트 측 유효성 검사를 방출에 대한 책임을 질 것입니다 사용자 정의 속성에 adapater를 연결하려면 다음 줄을 추가합니다 :

DataAnnotationsModelValidatorProvider.RegisterAdapter(
    typeof(SsnAttribute), 
    typeof(RegularExpressionAttributeAdapter) 
); 

이 구현되는 방식 RegularExpressionAttribute입니다 필요한 이유 . IClientValidatable 인터페이스를 구현하지는 않지만 대신 그것에 연결된 RegularExpressionAttributeAdapter이 있습니다.

RegularExpressionAttribute에서 파생 된 사용자 지정 특성이 있지만 클라이언트 유효성 검사가 작동하지 않거나 속성이 IClientValidatable 인터페이스를 구현하지 않았거나 (부모 클래스와 반대로) 연결된 특성 어댑터를 가지고 있지 않은 경우, . 따라서 SsnAttributeIClientValidatable 인터페이스를 구현하거나 앞에서 설명한 대답과 관련된 어댑터가 있어야합니다.

개인적으로이 사용자 지정 유효성 검사 특성을 구현하는 데 많은 부분이 보이지 않습니다. 상수는이 경우에 충분한 수 있습니다 : 다음

public const string Ssn = @"^(?!000)(?!666)(?!9[0-9][0-9])\d{3}[- ]?(?!00)\d{2}[- ]?(?!0000)\d{4}$", ErrorMessage = "The SSN you entered is invalid. If you do not have this number please leave the field blank"; 

과 :

public class FooModel 
{ 
    [RegularExpression(Ssn, ErrorMessage = "The SSN you entered is invalid. If you do not have this number please leave the field blank")] 
    public string Ssn { get; set; } 
} 

꽤 읽을 것 같다.

+2

필자의 속성이 IClientValidatable을 구현하게되었습니다. 'RegularExpressionAttribute'를 사용하는 대신에 이것을위한 속성을 원했던 이유는 주로 프로젝트에'public const string' 정규 표현식을 넣을 곳을 찾기를 원하지 않았기 때문입니다 ([Computer Science ...] (http://martinfowler.com/bliki/TwoHardThings.html)) 또한, MVC 사람들이 기본적으로 'RegularExpressionAttribute' (' PhoneAttribute ','EmailAddressAttribute' 등), 나는 정당하다고 느꼈다. –

관련 문제