2017-08-16 135 views
1

在我們的ASP.MVC項目中,我們使用DataAnnotations屬性進行驗證。其中一個字段應包含Url,並用[Url]屬性標記。但是,如果我將http://localhost:13030置於字段值中,則不會通過驗證。Url驗證屬性將`localhost`標記爲無效Url

有什麼方法可以使用該屬性來定義localhost作爲有效的目標?

+0

你的意思是'http:// localhost'吧?因爲「本地主機」本身不是一個有效的網址。 – reckface

+0

當然,我的意思是像'http:// localhost:13030'只是使用'localhost'來簡化。編輯問題 – ASpirin

回答

1

UrlAttribute根據源代碼中顯示的RegEx進行驗證:https://github.com/Microsoft/referencesource/blob/master/System.ComponentModel.DataAnnotations/DataAnnotations/UrlAttribute.cs#L46

http://localhost由於缺少.而不匹配。

看到這個答案的其他選項:How I can validate urls in C# for localhost

編輯:根據源代碼,您可以將dataAnnotations:dataTypeAttribute:disableRegEx添加到您的AppSettings並將其值設置爲true。這將導致UrlAttribute驗證過程到只有檢查它是否從http://,https://ftp://開始。請參閱相同源文件的Line 33

+0

感謝您的回答,我看過您提到的帖子。但是更多的問題是我們可以更改/配置確切的屬性。 – ASpirin

+0

@ASpirin我已回覆您的評論,並在我的回答中進行修改。 –

+0

將''添加到'appSettings'中,但結果相同,我會仔細檢查並返回給您 – ASpirin