Contracts like that are perfectly legal, in the same way that you're obligated to stay in the army for X number of years if you accept a military scholarship.
A lot of companies have clauses like that in their contracts if they provide specialized training. They want to get something out of you after they make an investment, afterall.