The pregnancy of Mary takes place before she went to live with Joseph, not because of a human deviation, but because of the divine will. God himself made fun of the law of legal purity in such a way as to make the Messiah be born among us!
If Joseph had acted according to the requirements of the law of that time, he would have had to denounce Mary and possibly she would have been stoned. Pregnancy before marriage is irregular and according to the law of legal purity, she should be punished with the death penalty (Deut 22:20).
But Joseph, because he is just, does not obey the requirements of the law of purity. His justice is greater. Instead of denouncing, he prefers to respect the mystery which he does not understand and decides to abandon Mary in secret. The greatest justice of Joseph saves both the life of Mary and that of Jesus.
Thus, Matthew sends an important message to the communities of Palestine and Syria. It is as if he said, "Behold, what would happen if the rigorous observance were followed, which certain Pharisees demand from you! They would put the Messiah to death!" Later Jesus will say, "If your justice is not greater than that of the Scribes and Pharisees, you will not enter into the Kingdom of Heaven" (Mt 5:20).