RegularExpression Validation属性无法正常工作 [英] RegularExpression Validation attribute not working correctly

查看:139
本文介绍了RegularExpression Validation属性无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to validate a property in my viewmodel to match a regular expression.

视图模型:

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是否以字母数字字符结尾,后跟/ \ .

The regular expression should check if the FilePath ends with a alphanumeric character followed by / or \.

在Regex101.com上链接到Regex

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

On Regex101.com this seems to work fine. However when I test this in my application it seems to never match the expression and the error message keeps showing up.

我在这里俯瞰什么?

推荐答案

RegularExpressionAttribute requires the full sting match:

//我们正在寻找完全匹配的内容,而不仅仅是搜索匹配.这符合什么
//RegularExpressionValidator控件
return(m.Success& m.Index == 0&&m.Length == stringValue.Length);

因此,您需要删除标志(这是一个错字),并在模式之前使用 ^.* :

So, you need to remove the flags (that is a typo) and use ^.* before your pattern:

@"^.*[a-zA-Z0-9][/\\]$"

这篇关于RegularExpression Validation属性无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆