How can I restrict users from entering special characters and numbers in the text box. I want only alphabets to be entered ( Typed / Pasted ).
give me sample javascript codes?
How can I restrict users from entering special characters and numbers in the text box. I want only alphabets to be entered ( Typed / Pasted ).
give me sample javascript codes?
Share Improve this question asked Apr 12, 2012 at 5:22 Febin ThomasFebin Thomas 581 gold badge2 silver badges9 bronze badges 2- so if i were Japanese, or Korean, would you block me? If I legitimately used a special character for a person's name, would you still block me? There are a lot of languages in the world, you can't keep track of all the "special characters". – Joseph Commented Apr 12, 2012 at 5:25
- possible duplicate of should i screen out odd characters from names – Joseph Commented Apr 12, 2012 at 5:37
3 Answers
Reset to default 2Take a look at this question: Function to return only alpha-numeric characters from string?
This is what you're after:
$result = preg_replace("/[^a-zA-Z0-9]+/", "", $inputVar);
If you're inserting that into the database after that, be sure to use something like mysql_real_escape_string()
or prepared statements.
Relying on Javascript solely for character validation is a very bad practice since JS can easily be disabled, and is not enabled on all devices globally.
Rather than preventing the entry of certain characers, it is far more user friendly and effective to validate the value when the form is submitted. You really don't care what the value of the field is before that, and you don't need special handling for how the value is entered. It might be pasted, dragged, auto-entered, entered by a plugin or script, or other methods.
A trivial example:
</script>
<form onsubmit="return validate(this);">
<input type="text" name="foo">
<input type="submit">
</form>
<script type="text/javascript">
function validate(form) {
var re = /^[a-z,A-Z]+$/i;
if (!re.test(form.foo.value)) {
alert('Please enter only letters from a to z');
return false;
}
}
</script>
You can try this, I'm using this right now for my current project
$(document).ready(function(){
/* Allow integers only in form input field with id #selector */
$('#selector').keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
})
It also doesn't allow the copy paste, but the weakness is the right click then paste
Disclaimer: I just found it from the internet