Be and Mg have zero value of electron affinity, because :
Know your College Admission Chances Based on your Rank/Percentile, Category and Home State.
Get your JEE Main Personalised Report with Top Predicted Colleges in JoSA
Be and Mg have [He] 2s2 and [Ne] 3s2 fully filled configuration respectively.
2s and 3s orbitals are filled to their capacity and they don't need any more electron to gain stability.
Be and Mg are unable to accept electron because they want to lose an electron to get the nearest nobel gas configuration.