0

In the JQuery Validate plugin, you can validate file extensions like this:

 $("#my-form").validate({
        rules: {
            file: {
                required: true,
                extension: "xls|csv"
            }
        });

I have a list of valid extensions in my MVC application that I use server side, and I thought it'd be neat to only maintain it in one place. So I tried to do this:

 $("#my-form").validate({
        rules: {
            file: {
                required: true,
                extension: @string.Join("|", new FileHelper().ValidFileExtensions))
            }
        });

But that fails because it's not wrapped in quotes. However, this:

extension: @string.Format("\"{0}\"", string.Join("|", new FileHelper().ValidFileExtensions)))

Results in the MVC engine rendering the quotes as " markup.

Can I get my file extensions wrapped in quotes?

Bob Tway
  • 9,301
  • 17
  • 80
  • 162
  • What your currently doing will only ever give you client side validation which can be easily overridden and you would need to repeat your logic again in the controller. Suggest you consider a validation attribute to give you both client and server side validation - refer [this answer](http://stackoverflow.com/questions/33414158/checking-image-mime-size-etc-in-mvc/33426397#33426397) for an example –  May 13 '16 at 00:49
  • @StephenMuecke I'd already put in server-side validation with a simple check for Request.Files[].FileName > error page. I wanted to keep all my client-side validation together in jQuery validate rather than use the built in mvc stuff for some of it. – Bob Tway May 13 '16 at 08:12

2 Answers2

1

The quotes are client-side, not server-side. Just put them directly in the client-side code like you would for any other string literal:

extension: '@string.Join("|", new FileHelper().ValidFileExtensions))'
David
  • 208,112
  • 36
  • 198
  • 279
  • Ah, I had assumed the right-hand comma would be interpreted as part of the compiled command. Thanks. – Bob Tway May 13 '16 at 08:10
0

Declare variable in Your view like this:

@{
   string validation = string.Format("\"{0}\"", string.Join("|", new FileHelper().ValidFileExtensions)));
 }

And use like this:

extension: @validation