Restrict users from entering special characters and numbers

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?

Answers


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>

Take 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.


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


Need Your Help

Changing a version in iTunes connect before it goes live

ios itunesconnect itunes-store itunes-app

I have an app that has been submitted to the app store in iTunes connect and approved but not yet released. (The release date is set in the future). The version number is 1.0.0.

rails testing fails to recognize path

ruby-on-rails ruby testing capybara

I am testing test/models/user_test.rb with