Can we use scales that belong to the chord that is in the scale you planned your composition to be in? For example I'm in a G major chord and there is a D major chord too, can I use the D major scale?
First of all, since this is your composition, you can do whatever you want. Unless you're going for something very specific, like you want to write your song in a certain style, there are no limits. Go nuts.
In your example, I assume you're in the G major key, and you have a D major chord, right? If this is the case, then yes you can freely use the D mixolydian scale. That is like the D major scale with a C natural instead of C#. You can use this scale because it's the V of G. It uses the same notes, but starts off at a different note
I stand with Shevliaskovic on this: You can indeed do what ever you want. Taking your question as written, that is the exact correct response.
However, I believe that this is what you really wanted to know:
It is true that G Major key has a D Major chord as the dominant (fifth chord of the key), and that D Major key has G Major chord as the sub-dominant (fourth chord of the key). This means yes for your specific case, without qualification. If you try, you can find scales and chords that do not match so well as this. G Major and D Major share all notes except C which is Sharp in D Major and natural in G Major.
It is important to note that you can find chords in the D major or G major scale that have a C# or a C natural. Take the C Major Chord In G major. The C Major chord would sound harsh against the Scale of D Major in most cases, while the D Major chord would sound fine played in the context of a C Major chord. This is proof by negation, that the answer to the OP is "no" because it is not true in all cases of chords and scales based on chords.
BTW Shevliaskovic is absolutely correct as well. You could say my answer is a translation of his. If you do not speak Mode, than learn modes. Learning modes is the deep answer to your question. Your question is an answer (not the only one) to the question "Why should I learn modes?"
Adding further to the two existing answers, the notes of MODES will fit slightly better than the notes of each major scale. On chord G, obviously, the G scale notes fit best. Still in the KEY of G, but on a D chord, the notes of D Mixolydian are a (slightly) better fit, and on a C chord, the notes from C Lydian likewise.
So, what's happening is that on each chord, the notes from the particular mode are best fit. And actually, they're the exact same notes from G major! It's just that they're centred round a different 'home'.
You can use the notes from each major scale, and make them all fit, but care is needed. It can really spice up the melody line if you do this, but ears are the best judges. Don't be bound by rules - what rules!- the theory has been formulated based on what usually works well, so it's a great guideline, but not the law.