【发布时间】:2018-09-08 10:50:58
【问题描述】:
我想验证视图模型中的属性以匹配正则表达式。
视图模型:
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 上,这似乎工作正常。 但是,当我在我的应用程序中测试它时,它似乎永远不会匹配表达式并且错误消息不断出现。
我在这里俯瞰什么?
【问题讨论】:
-
试试
@".*[a-zA-Z0-9][/\\]$" -
@WiktorStribiżew 有什么区别?他在正则表达式的开头没有
^,因此不需要完全匹配。 -
@tchelidze 整个区别在于该模式用于RegularExpressionAttribute。好吧,如果在服务器端进行验证,OP需要
@"(?i).*[a-zA-Z0-9][/\\]$" -
@WiktorStribiżew 所以如果我理解正确,RegularExpressionAttribute 会强制您使用匹配整个字符串的正则表达式?
-
是的。这是主要问题,而不是标志的错字。
标签: c# regex validation asp.net-core