Search code examples
c#javascriptregexasp.net-mvc-3unobtrusive-validation

Recognize a valid youtube url via unobtrusive validation regular expression is not working in MVC 3


I can't find a way to get through this error.

I've got 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 this case test

  • 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 the regex in a custom editor or even in a controller, I've a got a match for every case.

What is wrong with this code?


Solution

  • The correct RegExp is

    (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 check the whole line of RegExp and expect a correct match from the beginning to the end.