客户端验证不支持使用Unicode进行ASP.NET MVC Regex验证

时间:2015-12-23 04:36:53

标签: regex asp.net-mvc unobtrusive-validation validationattribute

我想验证一个给定的字符串,用于在服务器中保存具有所需名称的文件。

这要求我使用以下REGEX:^[\p\w\-. ]+$ 这很有效但只适用于英文字符串。

所以我修改了它^[\p{L}\w\-. ]+$ {L}修饰符被设置为接受任何Unicode字符。

这是视图模型。

[Required(ErrorMessageResourceType = typeof(FilesRepositoryStrings), ErrorMessageResourceName = "EnterTheNamePlease")]
[Display(ResourceType = typeof(FilesRepositoryStrings), Name = "FileNameInputLabel")]
[RegularExpression(@"^[\p{L}\w\-. ]+$", ErrorMessage = @"The file name can only contain letters, numbers and characters -_.")]
public string FileName { get; set; }

这是html渲染

<input class="form-control" data-val="true"
data-val-regex="The file name can only contain letters, numbers and characters -_." 
data-val-regex-pattern="^[\p{L}\w\-. ]+$" 
data-val-required="הזן את השם בבקשה" 
id="UploadFileModel_FileName" 
name="UploadFileModel.FileName" 
onkeyup="$('#EnterTheNamePlease').attr('hidden', true);" 
type="text" value="" 
aria-required="true" aria-invalid="true">

但客户端验证不接受任何Unicode(希伯来语)字符串..

任何克服这个问题的方法?

2 个答案:

答案 0 :(得分:0)

您可以使用/u flag在Javascript RegExp中激活Unicode支持。它是ECMAScript6的一部分,但根据this table,它在主流浏览器中尚不支持。

这很麻烦,但您可以做的是用自定义正则表达式引擎(如XRegexp)替换客户端验证。它支持unicode characters。在他们的示例中,他们使用简写符号\pL,但也支持\p{L}(根据this, chapter Unicode Categories)。

我还没有经过全面测试,可能会产生副作用。但我认为你可以做的是替换文件jquery.validate.unobtrusive.js中的RegExp匹配

match = new RegExp(params).exec(value);
return (match && (match.index === 0) && (match[0].length === value.length));

通过

var unicodeWord = XRegExp(params);
return unicodeWord.test(value);

您需要包含这些文件才能使其正常工作:

<script src="src/xregexp.js"></script>
<script src="src/addons/unicode-base.js"></script>
<script src="src/addons/unicode-categories.js"></script>
<script src="src/addons/unicode-scripts.js"></script>

当jquery验证发展时,当然很难维护,但它可能是一个解决方案。

答案 1 :(得分:0)

除了之前的回答 - 用于node.js的XRegExp.js,要在ASP.NET MVC中使用,你需要XRegExp版本作为纯java脚本运行,没有模型,我在这里找到它:

https://github.com/nagaozen/asp-xtreme-evolution/blob/master/lib/axe/classes/Utilities/xregexp.asp

Code拥有开源许可证。 我从答案中尝试了这个代码和解决方案,一切正常......