簡體   English   中英

為什么模式不適用於 cshtml (razor) asp.net?

[英]why does pattern not work for cshtml (razor) asp.net?

這是我的注冊頁面的 cshtml 代碼:

<div class="form-group">
    <label asp-for="Input.Name"></label>
    <input asp-for="Input.Name" class="form-control" pattern="[A-Za-z{3}]" />
    <span asp-validation-for="Input.Name" class="text-danger"></span>
</div>

這是輸入模型:

public class InputModel
{
    [Required]
    [StringLength(50, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 3)]
    [DataType(DataType.Text)]
    [Display(Name = "Name")]
    public string Name { get; set; }
}

每當我提交時,如果長度為 <3 或 >50,我確實會從輸入模型收到錯誤消息,但是,名稱不允許包含任何特殊字符或數字,我該怎么做? 提前致謝!

您可以將[RegularExpression]驗證屬性與僅允許字母( azAZ )字符的正則表達式結合使用。

例子:

public class InputModel
{
    [Required]
    [StringLength(50, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 3)]
    [DataType(DataType.Text)]
    [Display(Name = "Name")]
    [RegularExpression(@"^[a-zA-Z]+$", "Please only enter letters")]
    public string Name { get; set; }
}

但是如果你真的想在輸入上使用 HTML pattern屬性,你在模式中犯了一個小錯誤:

<input asp-for="Input.Name" class="form-control" pattern="[A-Za-z{3}]" />

應該:

<input asp-for="Input.Name" class="form-control" pattern="[A-Za-z]{3}" />

請注意{3}所在位置(方括號外)的細微差別。 有關更多信息,請參閱此文檔: https : //www.w3schools.com/tags/att_input_pattern.asp

請為帶有 asp-for 的剃刀頁面使用以下屬性

  1. 數據值正則表達式
  2. 數據值正則表達式模式

例子:

data-val-regex="Phone/Mobile number must be 10 digits." data-val-regex-pattern="^(?:.*[0-9]){10,}$"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM