문제

MVC의 세계에는이보기 모델이 있습니다 ...

public class MyViewModel{

[Required]
public string FirstName{ get; set; }    }

... 그리고 내 견해로는 이런 종류의 것 ...

<%= Html.ValidationSummary("Please correct the errors and try again.") %>
<%= Html.TextBox("FirstName") %>
<%= Html.ValidationMessage("FirstName", "*") %>

내 질문 : 이름을 공급하지 않고이 양식을 제출하면 "FirstName 필드가 필요하다"는 다음 메시지를받습니다.

확인. 그래서 나는 가서 내 재산을 ...

[DisplayName("First Name")]
[Required]
public string FirstName{ get; set; }    

.. 이제 "이름 필드가 필요합니다"를 얻습니다.

지금까지 모두 좋은.

이제 오류 메시지가 "이름 Blah Blah"를 표시하기를 원합니다. 기본 메시지를 displayName + "blah blah"로 비난하는 방법, Wihtout은 모든 속성에

[Required(ErrorMessage = "First Name Blah Blah")]

건배,

etfairfax

도움이 되었습니까?

해결책

public class GenericRequired: RequiredAttribute
{
    public GenericRequired()
    {
        this.ErrorMessage = "{0} Blah blah"; 
    }
}

다른 팁

다음은 서브 클래싱없이 수행하는 방법입니다 RequiredAttribute. 속성 어댑터 클래스 만 만드십시오. 여기에서 사용하고 있습니다 ErrorMessageResourceType/ErrorMessageResourceName (리소스와 함께) 그러나 쉽게 설정할 수 있습니다. ErrorMessage, 또는이를 설정하기 전에 재정의가 있는지 확인하십시오.

Global.asax.cs :

public class MvcApplication : HttpApplication {
    protected void Application_Start() {
        // other stuff here ...
        DataAnnotationsModelValidatorProvider.RegisterAdapter(
            typeof(RequiredAttribute), typeof(CustomRequiredAttributeAdapter));
        DataAnnotationsModelValidatorProvider.RegisterAdapter(
            typeof(StringLengthAttribute), typeof(CustomStringLengthAttributeAdapter));
    }
}

private class CustomRequiredAttributeAdapter : RequiredAttributeAdapter {
    public CustomRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
        : base(metadata, context, attribute)
    {
        attribute.ErrorMessageResourceType = typeof(Resources);
        attribute.ErrorMessageResourceName = "ValRequired";
    }
}

private class CustomStringLengthAttributeAdapter : StringLengthAttributeAdapter {
    public CustomStringLengthAttributeAdapter(ModelMetadata metadata, ControllerContext context, StringLengthAttribute attribute)
        : base(metadata, context, attribute)
    {
        attribute.ErrorMessageResourceType = typeof(Resources);
        attribute.ErrorMessageResourceName = "ValStringLength";
    }
}

이 예제는 Resources.resx라는 리소스 파일을 작성하게됩니다. ValRequired 새로운 필수 기본 메시지로 ValStringLength 문자열 길이가 기본 메시지를 초과함에 따라. 둘 다, {0} 필드의 이름을 수신하여 설정할 수 있습니다. [Display(Name = "Field Name")].

필요한 조치가 ICLientValidatable을 구현하지 않으므로 필요한 입력을 무시하면 클라이언트 측 유효성 검사를 중단합니다.

이것이 제가 한 일이며 작동합니다. 이것이 누군가를 돕기를 바랍니다.

public class CustomRequiredAttribute : RequiredAttribute, IClientValidatable
{
    public CustomRequiredAttribute()
    {
        this.ErrorMessage = "whatever your error message is";
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = this.ErrorMessage,
            ValidationType = "required"
        };
    }
}

그냥 변경하십시오

[Required] 

에게

[Required(ErrorMessage = "Your Message, Bla bla bla aaa!")]

편집 : 나는 [필수] 속성 으로이 솔루션을 찾고 있었고 그것을 찾는 데 문제가 있었기 때문에 이것을 게시했습니다. 새로운 Q/A를 만드는 것은이 질문이 이미 존재하기 때문에 그렇게 좋아 보이지 않습니다.

나는 같은 것을 해결하려고 노력했고 MVC 4에서 매우 간단한 솔루션을 발견했습니다.

먼저, 당신은 아마도 어떤 곳에 오류 메시지를 저장해야 할 것입니다. 나는 잘 설명 된 맞춤형 리소스를 사용했습니다 http://afana.me/post/aspnet-mvc-internationalization.aspx.

중요한 것은 간단히 ResourcesProject.Resources.SomeCustomError 또는 ResourcesProject.Resources.MainPagetitle 등. 자원 수업에 액세스하려고 할 때마다 현재 스레드에서 문화 정보를 가져 와서 올바른 언어를 반환합니다.

필드 검증에 오류 메시지가 있습니다 ResourcesProject.Resources.RequiredAttribute. 이 메시지를 볼 수 있도록 설정하려면이 두 매개 변수로 [필수] 속성을 업데이트하십시오.

errormessageresourceType - 호출 될 유형 (예에서 resources project.resources)

errormessageresourcename입니다 - 위의 유형에 호출되는 속성 (우리의 경우 필요한 입력)

다음은 매우 단순화 된 로그인 모델이며 사용자 이름 유효성 검사 메시지 만 표시합니다. 필드가 비어 있으면 문자열이 ResourcesProject.Resources.RequiredAttribute 이것을 오류로 표시합니다.

    public class LoginModel
    {        
        [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName="RequiredAttribute")]
        [Display(Name = "User name")]
        public string UserName { get; set; }
}

자신의 속성을 쓸 수 있습니다.

public class MyRequiredAttribute : ValidationAttribute
{
    MyRequiredAttribute() : base(() => "{0} blah blah blah blaaaaaah")
    {

    }

    public override bool IsValid(object value)
    {
        if (value == null)
        {
            return false;
        }
        string str = value as string;
        if (str != null)
        {
            return (str.Trim().Length != 0);
        }
        return true;
    }
}

오류 메시지가 변경된 반사기의 필수 Attribute 사본입니다.

using Resources;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Web;
using System.Web.Mvc;

public class CustomRequiredAttribute : RequiredAttribute,  IClientValidatable
{
    public CustomRequiredAttribute()
    {
        ErrorMessageResourceType = typeof(ValidationResource);
        ErrorMessageResourceName = "RequiredErrorMessage";
    }


    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {


        yield return new ModelClientValidationRule
        {
            ErrorMessage = GetRequiredMessage(metadata.DisplayName),
            ValidationType = "required"
        };
    }


    private string GetRequiredMessage(string displayName) {

        return displayName + " " + Resources.ValidationResource.RequiredErrorMessageClient;        

    }


}

app_globalresources/validationResource.resx

enter image description here

이제 데이터 주석을 사용하십시오

[CustomRequired]

이것은 나를 위해 효과가있었습니다. 코드 내에서 주석을주의 깊게 읽으십시오. (차드의 대답에 근거).

 // Keep the name the same as the original, it helps trigger the original javascript 
 // function for client side validation.

        public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute, IClientValidatable
            {
                public RequiredAttribute()
                {
                    this.ErrorMessage = "Message" // doesnt get called again. only once.
                }

                public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
                {
                    yield return new ModelClientValidationRule
                    {
                        ErrorMessage = "Message", // this gets called on every request, so it's contents can be dynamic.
                        ValidationType = "required"
                    };
                }
            }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top