5

I want to validate a given string that will be used to save the file with the required name in the server.

this requires me to use the following REGEX:^[\p\w\-. ]+$ which works great but only for English strings.

so I have modified it like this ^[\p{L}\w\-. ]+$ the {L} modifier is set to accept any Unicode character.

this is the view-model.

[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; }

this is the html render

<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">

but the client-side validation is not accepting any Unicode (Hebrew) strings..

any ways to overcome this ?

Sparky
  • 98,165
  • 25
  • 199
  • 285
Mortalus
  • 10,574
  • 11
  • 67
  • 117

2 Answers2

0

You can activate Unicode support in Javascript RegExp with the /u flag. It is part of ECMAScript6 but according to this table it is not supported yet in the major browsers.

It is hacky but what you could do is to replace the client side validation with a custom regular expression engine like XRegexp. It is supporting unicode characters. In their example they use shorthand notation \pL but \p{L} is also supported (according to this, chapter Unicode Categories).

I haven't entirely tested and it might have side effects. But I think what you can do is to replace the RegExp matching in file jquery.validate.unobtrusive.js

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

by

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

You need to include these files to make it work:

<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>

Of course it will be difficult to maintain when jquery validate evolves but it could be a solution.

Fabian
  • 1,886
  • 14
  • 13
0

In addition to the previous answer- XRegExp.js used for node.js, to use in ASP.NET MVC you need XRegExp version that operates as a pure java script, without model, I found it here:

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

Code has an open source license. I tried this code and solution from the answer and everything works fine...