2011-09-08 29 views
4

此問題之前已被詢問過,但我認爲搜索條件對我來說太過籠統,無法找到我正在尋找的答案,所以我會再問一次。如果用戶在int字段中輸入非數字字符串,則會自定義驗證錯誤消息

我有一個int屬性和範圍註釋模型。

如果用戶輸入的內容不是int,驗證消息以The value '<bad data>' is not valid for '<property name>'作爲響應......這很好,但我想提供更多的反饋信息,即Expecting an integer value in this field.

由於此驗證失敗之前,其他驗證程序看一看,我不知道如何(或者如果有可能)覆蓋默認驗證器消息。

我有什麼選擇?

每個請求,我張貼的代碼,但不是很多吧:

[Range(0,65535, ErrorMessage="Port must be between 0 and 65535.")] 
public int Port { get; set; } 

存在着發生到達RangeAttribute之前驗證。我想用我自己選擇的一個替換默認消息。

+0

發佈包含註釋的int聲明的實際代碼。 – Cymen

+0

完成,雖然我不知道它會做多少好事。 –

回答

3

如果您使用的是標準的註釋,你應該能夠像這樣重寫錯誤消息:

[MyAnnotation(...., ErrorMessage = "My error message")] 
public int myInt { get; set; } 

還是你真正想要追加到默認的錯誤消息,而不是取代它的(不清楚問題)?

更新:誤讀 - 表明這爲答案:How to change the ErrorMessage for int model validation in ASP.NET MVC?或更好,但How to change 'data-val-number' message validation in MVC while it is generated by @Html helper

+0

驗證錯誤消息發生在驗證器之前。 –

+0

啊!誤讀 - 我想你想這個然後:http://stackoverflow.com/questions/6587816/how-to-change-the-errormessage-for-int-model-validation-in-asp-net-mvc – Cymen

+1

這是另一種選擇 - 它實際上也有一個公認的答案:http://stackoverflow.com/questions/4828297/how-to-change-data-val-number-message-validation-in-mvc-while-it-generate-他/ 6405298#6405298 – Cymen

1

閱讀this question。在OP建議的鏈接中,您將找到替換使用該框架的deafult錯誤字符串的方法,而在答案中,如果您想要更改所有這些字符串,則會在其他資源中找到linnk。也請看here。希望它有幫助

+0

是的,更新資源文件是離我最遠的;此外,由於不同的類型轉換錯誤,它似乎不支持分支。 –

+0

猜你必須編寫自己的擴展名,就像你已經找到的答案一樣。對不起 – Iridio

3

你也可以在模型類中繼承IValidatableObject。您可以在Validate方法中寫下您所需的邏輯。請在下面找到示例代碼。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.ComponentModel.DataAnnotations; 

namespace MvcApplication1.Models 
{ 
    public class Alok : IValidatableObject 
    { 
     [Display(Name = "Property1")] 
     [Required(AllowEmptyStrings = false, ErrorMessage = "Property1 is required.")] 
     public int Property1 { get; set; } 

     [Display(Name = "Property2")] 
     [Required(AllowEmptyStrings = false, ErrorMessage = "Property2 is required.")] 
     public int Property2 { get; set; } 

     public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
     { 
      if (Property1 < Property2) 
      { 
       yield return new ValidationResult("Property 1 can't be less than Property 2."); 
      } 
     } 
    } 
} 
+1

我不認爲這會奏效。驗證錯誤在「官方」驗證之前的映射時間添加到模型中。 –

相關問題