No. I’m not sure why you’ve chosen to frame this as a question of “legality”. Primaries are creatures of state law. How could a law be illegal? Perhaps you are thinking that primaries are unconstitutional. If so, why? What provision of state or federal constitutions do you think they might violate?
Governments spend money in thousands of different ways that benefit private individuals and organizations. Perhaps you think primaries violate equal protection guidelines, since the state holds primaries for some parties but not others. If so, be aware that the laws are always written such that a primary will be held for any party that attains a certain percentage of the vote, and states can and have held primaries for third parties after those parties surpassed the threshold in a particular race.
One might certainly question whether it is appropriate for states to conduct elections to determine party nominees. Indeed, I’ve done so myself. To address that question, it helps to understand why direct primaries were instituted. (The best book on the topic is The American Direct Primary, by Alan Ware.)
During the Nineteenth Century, parties nominated candidates at city, state, and district conventions. Some of the more local conventions were open to any party member that showed up, whereas at the larger (state) conventions, you had to get elected at a delegate from one of the local gatherings.
After nominations were made, the party would print up tickets, district by district, with the names of its candidates. You would vote any dropping your ticket into a ballot box on Election Day.
Disputes at conventions were frequent. Sometimes, the losing faction would print up its own tickets and claim they were the rightful nominees. There was nothing to prevent this.
Then between 1870 and 1890, American states adopted the Australian Ballot. Under the Australian Ballot, the state prints ballots which list all of the candidates from every party which meets ballot requirements, and voters place a check (or later, pull a lever or punch a hole) by the candidates for whom they vote.
And presto, every party dispute over a nomination became the responsibility of the state. The state had to decide who was the legitimate party nominee, and who belonged on the ballot. Rules multiplied, but disputes continued.
To many good-government types in the late 1800’s and early 1900’s–and even to many party professionals weary of convention wrangling–a state-run primary seemed like the cleanest and best solution. The state already knew how to conduct elections; why not do it for nominations as well? The cost was trivial, and little more than the cost of refereeing endless convention nomination disputes.
By 1920, virtually every state had adopted the direct primary for offices other than President.
Please forgive the length of my response but there is a lot of confusion over the origin of direct primaries and it’s hard to debate their efficacy without understanding how they came to be.