It is legal and enforceable. Employers and employees may contract for the employee to pay back various costs (e.g. training costs; a signing or relocation bonus; recruiter costs; tuition reimbursment) if the employee leaves employment within a certain time frame. If you signed the contract and therefore agreed to it, it is legal.