8

It's not a JS question, just looking for a clear css solution if it's possible.

For a radio button or a checkbox we can use the :checked pseudo class:

input{
  % styles %
}
input:checked{
  % another styles %
}

Are there tricks for checking if a file attachment exists with CSS?

kittykittybangbang
  • 2,380
  • 4
  • 16
  • 27
KZee
  • 436
  • 4
  • 11
  • 11
    No. When using a file input, it sets the value of the element. There is currently no way of ascertaining whether an input element has a value or not in CSS. See http://stackoverflow.com/questions/16952526/detect-if-an-input-has-text-in-it-using-css If the file input is required, check those answers, you'll see a solution about setting the required attribute. – yts Aug 17 '15 at 02:03
  • Thank you. I expected this answer, but I wasn't sure. – KZee Aug 17 '15 at 02:15

1 Answers1

4

(updated, due to misunderstanding the question)

It is possible to check if a file was attached using the attribute required.

See: http://jsfiddle.net/1ua59jt1/1/

HTML:

<input id="file" type="file" name="fileselect" required="required" />

CSS:

#file:valid { color: green; }
#file:invalid { color: red; }

But you can never really validate, if a "correct" file was selected this way. You can only check if or if not a file was selected at all.


// completion update:

The required attribute is HTML5. Please be aware that not all browsers support this: http://www.w3schools.com/tags/att_input_required.asp

That means the only trusted way for client side validation is using javascript. If you want to do so, I recommend using the novalidate attribute on your form to disable the browsers default validation (http://www.w3schools.com/tags/att_form_novalidate.asp).

But always use server-side validation, too. You can never make sure the user has enabled jaavscript or hasn't manipulated javascript. So the best way is always to validate values on the side you have fully control over: the server, i.e. your action the form sends its data to.

Seika85
  • 1,981
  • 2
  • 18
  • 29
  • Again: "It's not a JS question, just looking for a clear css solution if it's possible." And full and correct answer was given in first comment. – KZee Sep 04 '15 at 14:18
  • I kind of read, that you want to check if a _valid_ file was selected. If you just want to determine via CSS if or if not any file was selected at all, you can use the attribute `required`for that. I updated my answer. Sorry for the misunderstanding. – Seika85 Sep 04 '15 at 14:23
  • Nice idea! It's not universal solution because required attribute not always possible, but sometime can be useful. – KZee Sep 04 '15 at 15:44