In Harry Potter the Chamber of Secrets, Hermione casts a spell to repair Harry's glasses. She also does the same in Harry Potter and the Philosopher's Stone. According to Magic Law, underage wizards are not allowed to do magic outside of Hogwarts. We also saw that Harry gets punishment for doing the same. Then why does Hermione not get any kind of punishment for casting magic outside Hogwarts?
There's a choice of possibilities... According to Dumbledore, the Ministry of Magic can detect when magic has been done near an underage wizard, but not who actually performed it. So on a train full of underage wizards it's perhaps just too difficult to enforce the rule.
More likely, the Hogwarts Express is deemed an extension of school property, so it's except from the rule. The rule is mainly there to protect the secrecy of the wizarding world anyway, and once you're on the Hogwarts Express the secret is pretty much already out.