var k;
document.all ? k = e.keyCode : k = e.which;
var ret = ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
document.getElementById("error").style.display = ret ? "none" : "inline";
return ret;
}
</script>
Example 2: How to validate special characters in text box using javascript?
function Validate_specialChar(id){
var yourInput = $('#'+id).val();
re = /[`"~!@#$%^&*()?|+\<>\{\}\[\]\\\/]/gi;
var isSplChar = re.test(yourInput);
if(isSplChar){
var no_spl_char = yourInput.replace(/[`"~!@#$%^&*()?|+\<>\{\}\[\]\\\/]/gi, '');
$('#'+id).val(no_spl_char);
$('#'+id+'_errr').text('Special Character not allowed');
}
}
function ValidatespecialChar(id){
var maxLength = 500;
var yourInput = $('#'+id).val();
re = /[`~!@#$%^&*()?|+\<>\{\}\[\]\\\/]/gi;
var isSplChar = re.test(yourInput);
if(isSplChar){
var no_spl_char = yourInput.replace(/[`~!@#$%^&*()?|+\<>\{\}\[\]\\\/]/gi, '');
$('#'+id).val(no_spl_char);
$('#'+id+'_errr').text('Special Character not allowed');
}
var textlen = maxLength - $('#'+id).val().length;
$('#'+id+'_errr').text(textlen+' Character remaining');
}
</script>
<script type="text/javascript">
function ValidatespecialChar(id){
var yourInput = $('#'+id).val();
re = /[`~!@#$%^&*()?|+\<>\{\}\[\]\\\/]/gi;
var isSplChar = re.test(yourInput);
if(isSplChar){
var no_spl_char = yourInput.replace(/[`~!@#$%^&*()|+\<>\{\}\[\]\\\/]/gi, '');
$('#'+id).val(no_spl_char);
}
}
</script>
Special characters validation, Allow alphanumeric , dash, underscore and space on keypress.
File name : index.php
<input onkeypress="return Validate(event);" type="text" /><br/>
<span style="color:red;" id="lblErrorMsg"></span>
<script>
function Validate(e) {
var keyCode = e.keyCode || e.which;
var errorMsg = document.getElementById("lblErrorMsg");
errorMsg.innerHTML = "";
//Regex to allow only Alphabets Numbers Dash Underscore and Space
var pattern = /^[a-z\d\-_\s]+$/i;
//Validating the textBox value against our regex pattern.
var isValid = pattern.test(String.fromCharCode(keyCode));
if (!isValid) {
errorMsg.innerHTML = "Invalid Attempt, only alphanumeric, dash , underscore and space are allowed.";
}