CustomAttributeValidation Guid中的ErrorMessage

时间:2016-11-01 19:06:57

标签: c# asp.net-mvc data-annotations custom-attributes modelstate

我需要帮助来自定义从Guid自定义属性验证类发送的ErrorMessage。

默认错误消息:" 值'(MyValue)' (MyProperty)无效。"。

它适用于其他数据类型,如:String,int,int?。

注意#1:仅当guid对象为null或无效时才会出现此问题。

注意#2:无效导致guid为null,官方文档说:

注意#3:IsValidGuid类中的这些方法都不起作用。

注意#4:如果Guid有效,我在dataannotation中的自定义ErrorMessage可以正常工作。

     Summary:
         Initializes a new instance of the System.Guid structure by using the specified
         array of bytes.

     Parameters:
       b:
         A 16-element byte array containing values with which to initialize the GUID.

     Exceptions:
       T:System.ArgumentNullException:
         b is null.

       T:System.ArgumentException:
         b is not 16 bytes long.

视图模型

public class ViewModel
{
    [Required(ErrorMessage = "Campo Obrigatório")]
    [IsValidGuid(ErrorMessage ="Guid inválida")]
    public System.Guid? MyGuid { get; set; }
}

IsValidGuid

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)]
    public class IsValidGuid : ValidationAttribute
    {
        //public override bool IsValid(object value)
        //{
        //    if (value == null)
        //    {
        //        return false;
        //    }

        //    Guid guidOutput;

        //    if (Guid.TryParse(value.ToString(), out guidOutput))
        //    {
        //        if (guidOutput.ToString().Equals("00000000-0000-0000-0000-000000000000"))
        //        {
        //            return false;
        //        }

        //        return true;
        //    }

        //    return false;
        //}

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {


            if (value == null)
            {
                return new ValidationResult(ErrorMessage ?? "Test");
            }

            Guid guidOutput;

            if (Guid.TryParse(value.ToString(), out guidOutput))
            {
                if (guidOutput.ToString().Equals("00000000-0000-0000-0000-000000000000"))
                {
                    return new ValidationResult(base.ErrorMessage);
                }

                return ValidationResult.Success;
            }

            return new ValidationResult(ErrorMessage ?? DefaultErrorMessage);
        }
    }

0 个答案:

没有答案
相关问题