0

내 페이지에 대한 클라이언트 쪽 유효성 검사 설정이 눈에 띄지 않습니다. 오류 메시지는 데이터베이스에서 반환됩니다. 유효성 검사 메시지 중 하나에 대해 매개 변수를 추가해야 특정 값으로 형식을 지정할 수 있습니다. 이 좋은 서버 쪽 작동하지만 GetClientValidationRules 메서드가 처음 설치 될 때 분명히 이러한 값 중 일부에 액세스 할 수 없습니다. 이 때문에 내 클라이언트 측 코드에서 오류 메시지를 작성해야 할 것 같지만 jQuery.validator.addMethod에서 true 또는 false를 반환하기 때문에이 작업을 수행하는 방법을 알지 못합니다.MVC3 및 사용자 지정 클라이언트 쪽 유효성 검사 메시지

그래서 기본적으로 할 수 있어야 할 것은 ErrorClassValidationRules 메서드에서 string.Empty로 ErrorMessage를 설정 한 다음 유효성 검사를 수행하는 임상가 측 코드에서 원하는 모든 메시지를 반환 할 수 있어야합니다. 여기

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
    { 
     var rule = new ModelClientValidationRule 
         { 
          ValidationType = "maximumdatecoverrequired", 
          ErrorMessage = string.Empty, 
         }; 

     rule.ValidationParameters.Add("maxdate", DateTime.Now.AddDays(Settings.Default.MaximumDateCoverRequiredDaysInFuture).ToString("yyyy/MM/dd")); 

     return new[] { rule }; 
    } 

다음이 특정 부동산에 대해 확인하는 나의 클라이언트 측 코드는

MVC 3에서 유선되는 클라이언트 측 코드입니다.

jQuery.validator.addMethod("maximumdatecoverrequired", function (value, element, params) { 
     var maxDate = new Date(params["maxdate"]); 
     var day = maxDate.getDate(); 
     var month = maxDate.getMonth() + 1; 
     var year = maxDate.getFullYear(); 

     var dateCoverRequired = new Date(value).toString('yyyy/MM/dd'); 
     maxDate = maxDate.toString('yyyy/MM/dd'); 

     if (value > maxDate) { 
      $("input#DateCoverRequired_Day").val(day); 
      $("select#DateCoverRequired_Month").val(month); 
      $("input#DateCoverRequired_Year").val(year); 
      return false; 
     } 

     return true; 
    }); 

클라이언트 측 코드로 맞춤 메시지를 반환하려면 어떻게해야합니까?

+1

유효성 검사를 하시겠습니까? 너무 많은 세부 사항이 누락되었습니다 – gdoron

+0

gdoron - 나는 내 질문을 내가 성취하려는 것으로 업데이트했습니다. – doogdeb

+0

@doogdeb, 다시 한 번 업데이트하고 이번에는 코드를 포함하는 것을 잊지 마십시오. –

답변

1

내가 어떻게하는지에 대한 예를 들어 보겠습니다. 내가 선택한 예제는 새 사용자를 등록하고 이름을 확인하는 것입니다.

우리가 할 일은 사용자가 UserName을 선택할 수 있도록 허용하고, 이미 데이터베이스에있는 경우 사용자가이를 허용하지 않고 제안을 할 것입니다.

이렇게하려면 컨트롤러의 ActionMethod를 가리키는 원격 유효성 검사를 사용합니다.

등록 모델

public class RegisterModel 
    { 
     //This is the one I'm giving you the code for... 
     [Required] 
     [RegularExpression(@"(\S)+", ErrorMessage = "Username cannot contain spaces.")] 
     [Remote("CheckUserName", HttpMethod="POST")] 
     [Display(Name = "Username")] 
     public string UserName { get; set; } 

     // You can do this one yourself :-) 
     [Required] 
     [Remote("CheckEmailAddress", ErrorMessage="{0} already has an account, please enter a different email address.", HttpMethod="POST")] 
     [DataAnnotationsExtensions.Email(ErrorMessage="{0} is not a valid email address.")] 
     [Display(Name = "Email address")] 
     public string Email { get; set; } 

     [Required] 
     [ValidatePasswordLength] 
     [DataType(DataType.Password)] 
     [Display(Name = "Password")] 
     public string Password { get; set; } 

     [DataType(DataType.Password)] 
     [Display(Name = "Confirm password")] 
     [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] 
     public string ConfirmPassword { get; set; } 
    } 

ActionMethod (모델에 의해 참조 원격 방법)

[HttpPost] 
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)] 
public JsonResult CheckUserName(string userName, Guid? userId = null) 
{ 
    if (userName != null || userName.Length > 2) 
    { 
     var users = Membership.FindUsersByName(userName); 
     if (users.Count == 0) 
     { 
       return Json(true); 
     } 
     else 
     { 
      if ((users[userName].ProviderUserKey as Guid?) == userId) 
      { 
       return Json(true); 
      } 
      else 
      { 
       string suggestedUID = String.Format(CultureInfo.InvariantCulture, "{0} is not available.", userName); 
       // Maybe this is a bit feeble, but it will loop around (inefficiently) and suggest a new username with a number on the end. EG Tom is not available. Try Tom37 
       for (int i = 1; i < 100; i++) 
       { 
        string altCandidate = userName + i.ToString(); 
        if (Membership.FindUsersByName(altCandidate).Count == 0) 
        { 
         suggestedUID = String.Format(CultureInfo.InvariantCulture, "{0} is not available. Try {1}.", userName, altCandidate); 
         break; 
        } 
       } 
       // This is the important bit. I am returning a suggested UserName 
       return Json(suggestedUID, JsonRequestBehavior.AllowGet); 
      } 
     } 
    } 
    else 
    { 
     return Json(true); 
    } 
} 

내가 정규식 만들기 때문에이, 정말 멋진 생각 있는지가 없음 공백을 입력 한 다음 (괜찮 으면) 데이터베이스를 검사하는 원격 메소드에 제출됩니다.

관련 문제