Recognizing a valid youtube URL through unobtrusive regex confirmation does not work in MVC 3

I cannot find a way to overcome this error.

I have this code in my model

MultimediaLanguageEdit.cs

public class MultimediaLanguageEdit { //[RegularExpression(@"((?<=^https?://(www\.)?youtube\.com/.*v=)\w+)|((?<=^https?://youtu\.be/)\w+)|((?<=src=""https?://(www\.)?youtube\.com/v/)\w+)|((?<=src=""https?://(www\.)?youtube\.com/embed/)\w+)", [RegularExpression(@"(^https?://(www\.)?youtube\.com/.*v=\w+)|(^https?://youtu\.be/\w+)|(src=.https?://(www\.)?youtube\.com/v/\w+)|(src=.https?://(www\.)?youtube\.com/embed/\w+)", ErrorMessageResourceType = typeof(ErrorMessages), ErrorMessageResourceName = "FieldRegExp")] public string Text { get; set; } } 

and this code in my view

MultimediaLanguageEdit.cshtml

 @model MultimediaLanguageEdit <div class="editor-label"> @Html.LabelFor(m => m.Text, "Codice HTML:") </div> <div class="editor-field"> @Html.TextAreaFor(m => m.Text) @Html.ValidationMessageFor(m => m.Text) </div> 

and the field is always invalid for all of these test tests

  • http://www.youtube.com/watch?v=tYTIo6H19uw&feature=grec_index
  • <iframe width="560" height="315" src="http://www.youtube.com/embed/tYTIo6H19uw" frameborder="0" allowfullscreen></iframe>
  • <object width="560" height="315"> <param name="movie" value="http://www.youtube.com/v/tYTIo6H19uw?version=3&amp;hl=it_IT"></param><param name="allowFullScreen" value="true"></param> <param name="allowscriptaccess" value="always"></param> <embed src="http://www.youtube.com/v/tYTIo6H19uw?version=3&amp;hl=it_IT" type="application/x-shockwave-flash" width="560" height="315" allowscriptaccess="always" allowfullscreen="true"></embed> </object>

and match this test case

but if I test the regular expression in a custom editor or even in a controller, I have a match for each case.

What is wrong with this code?

+4
source share
1 answer

Correct RegExp -

 (https?://(www\.)?youtube\.com/.*v=\w+.*)|(https?://youtu\.be/\w+.*)|(.*src=.https?://(www\.)?youtube\.com/v/\w+.*)|(.*src=.https?://(www\.)?youtube\.com/embed/\w+.*) 

Because javascript validates the entire RegExp string and expects the correct match from start to finish.

+2
source

Source: https://habr.com/ru/post/1379338/


All Articles