[英]RegularExpression Validation attribute not working correctly
我想驗證我的viewmodel中的屬性以匹配正則表達式。
視圖模型:
using System.ComponentModel.DataAnnotations;
namespace ProjectName.ViewModels
{
public class ViewModel
{
[Required(ErrorMessage = "error message.")]
[RegularExpression(@"[a-zA-Z0-9][/\\]$/img", ErrorMessage = "End with '/' or '\\' character.")]
public string FilePath { get; set; }
public ViewModel()
{
}
}
}
視圖:
@model ProjectName.ViewModels.ViewModel
<form asp-action="EditPath" asp-controller="Files" id="EditFilePathForm">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="col-md-5">
<div class="form-group">
<div class="col-md-12">
<label asp-for="FilePath" class="control-label"></label>
</div>
<div class="col-md-8">
<input asp-for="FilePath" class="form-control"/>
<span asp-validation-for="FilePath" class="text-danger"></span>
</div>
<div class="col-md-4">
<p>@Model.FileName</p>
</div>
</div>
</div>
<div class="col-md-12 text-right">
<hr />
<button type="button" class="btn btn-default" id="cancelEditFilePathModal" data-dismiss="modal">Annuleren</button>
<input type="submit" class="btn btn-primary" id="Submit" value="Opslaan"/>
</div>
</form>
正則表達式應檢查FilePath是否以字母數字字符結尾,后跟/
或\\
。
在Regex101.com上,這似乎工作正常。 但是,當我在我的應用程序中測試它時,似乎永遠不會匹配表達式,並且錯誤消息不斷出現。
我在這里俯瞰什么?
RegularExpressionAttribute
需要完整的sting匹配:
// We are looking for an exact match, not just a search hit. This matches what
// the RegularExpressionValidator control does
return (m.Success && m.Index == 0 && m.Length == stringValue.Length);
所以,你需要刪除標志(這是一個錯字)並在你的模式之前使用^.*
:
@"^.*[a-zA-Z0-9][/\\]$"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.