It's looks like all you want is alphanumerics "a-zA-Z_0-9" which are nice and safe.
First you could start on the client-side with a javascript:
function isEmpty(inputStr) {
if (inputStr == null || inputStr == "") {
return true
}
return false
}
function isUserID(inputStr) {
if (/\W/.test(inputStr)){
return (false)
}
return (true)
}
function checkForm(form) {
if(isEmpty(form.userid.value)){
alert("Please enter a User ID.")
return false
}
if(!isUserID(form.userid.value)){
alert("User ID should only contain letters, numbers and underscore characters..")
return false
}
}
and in the form's event handler is the following:
... onSubmit="return checkForm(this)" ....
Sever-side not much different:
if($_POST['userid']){
if(preg_match ("/\W/", $_POST['userid'])) {
// error in userid
} else {
// no error what's next
}
}
The \W matchs nonword characters, which you could change to "~!@#$%&*" if you want. (might need to escape a couple of those symbols)
Hope that helps?