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?

2
  • 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 for an example Commented May 13, 2016 at 0: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. Commented May 13, 2016 at 8:12

2 Answers 2

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))'
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, I had assumed the right-hand comma would be interpreted as part of the compiled command. Thanks.
0

Declare variable in Your view like this:

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

And use like this:

extension: @validation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.