A previous home owner installed a ceiling fan which appears well secured and works well. The wire to the fan was simply spliced into an existing wire using wire nuts but not enclosed in a junction box. I am certain that this is not up to code. The splice is nearly one foot from any joist. Can I just reconnect everything inside a box which is not secured to the frame or should I attach the box to a 2x4 that I can place between the joists?
The question is all about may the box be left floating or in other words must it be anchored somehow?
The answer is yes, a junction box needs to be supported by more than simply the cables going into it. But the bar isn't high. If you're working with drywall then mounting the box to the drywall itself is sufficient. The "old work box" exists for exactly this purpose. (image credit: lowes.com)
Another option is to use a box with a built-in spreader bar: these exist so that a box can be placed in just the right spot between framing members, like a light fixture that is to be centered in a certain location. (image: simsupply.com)
It's also acceptable to use lumber to create support for an ordinary nail-on box.
In all cases the objective is to adequately support the box, the cables, and any device that might be mounted to the box. If this box will support only wire nuts and a cover plate then the structure can be very simple and light.
On second reading of the question there may another problem that should also be addressed. If the fan's own fixture wires are stretched over to meet the building wire, ie the fan is not mounted to any sort of junction box, that's no good. Install an appropriate junction box to carry the weight of the fan, splice in that box to a building cable like NM-B, and splice that cable to the existing building wiring in a second box as described above.
Yes, it needs to be in an approved electrical box. It also needs to be a box that's rated to carry a rotating load. They make a retrofit ceiling fan box that had a screw mechanism that drives spikes into the joists capable of carrying a 50 lb rotating load.