RegularExpression Validation属性无法正常工作

Jer*_*oen 4 c# regex validation asp.net-core

我想验证视图模型中的属性以匹配正则表达式。

视图模型:

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()
        {

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

视图:

@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>
Run Code Online (Sandbox Code Playgroud)

正则表达式应检查FilePath是否以字母数字字符结尾,后跟/\

在Regex101.com上链接到Regex

在Regex101.com上,这似乎工作正常。但是,当我在应用程序中对其进行测试时,它似乎从不匹配表达式,并且错误消息不断出现。

我在这里俯瞰什么?

Wik*_*żew 7

RegularExpressionAttribute 需要完整的刺痛比赛:

// 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][/\\]$"
Run Code Online (Sandbox Code Playgroud)