A regular expression will be the perfect answer for this.
The following HTML code is all that you need:
<form>
<input type="text" name="username" required pattern="[0-9a-zA-Z_.-]*">
<input type="submit">
</form>
When you attempt to submit that with invalid characters, the form shows an error message saying “Please use the requested format.”
We can improve on that error message too, making it more specific:
var input = document.querySelector("[name=username]");
input.oninvalid = function(event) {
event.target.setCustomValidity("Special characters are not allowed.");
}
A simple demo is up at https://jsfiddle.net/pmw57/2zqcqpzx/