A man was arrested and charged after he tried to kidnap a baby from a train while allegedly under the influence of drugs on Sunday night, police said.

Rafael Martinez, 30, of Brooklyn, approached a woman and her 4-month-old baby girl on a J train in Brownsville at about 11 p.m., police said.

After making conversation, Martinez tried to grab the baby, who was strapped into a carrier, the girl’s mother told reporters. She and her mother-in-law struggled with Martinez until a good Samaritan on the train eventually helped her and restrained Martinez, she said.

Martinez was arrested at the Alabama Avenue station and later charged with attempted kidnapping, endangering the welfare of a child and criminal possession of a controlled substance, police said. He was believed to be under the influence at the time of the incident, they said.

Martinez has close to 20 prior arrests, cops said. Previous charges include robbery and drug possession, they said.