Preventing spammers is usually done using a CAPTCHA, which is basically a puzzle that is designed so that only real people can solve it, rather than bots that are designed to post spam.
A very commonly used solution is called reCAPTCHA. This will be good for many websites, although if your website would be best served by making registrations much easier (users who will not want to put much effort into joining the site), then you could use a simpler to use CAPTCHA such as this one. Generally, the harder the CAPTCHA is to solve for the user, the better it will be at stopping spammers.
Also note that regardless of how good your CAPTCHA is, a real human can still create an account and post spam. For these users, I recommend banning the account (disabling it so that it cannot submit new content).