Checking input for alphabetic characters only

I want to confirm my username input field, which does not allow me to enter a number or special characters inside. My html

<div class="form-group">
  <input type="text" name="username" id="display_name" class="form-control input-lg"
  placeholder="User Name" tabindex="3">
</div>

Javascript validation

username: {
  required: true,
  minlength: 5,
  maxlength: 15,
  remote: "ajax_val/val_username.php",
  notNumber: true 
 },
+4
source share
2 answers

You can use this regex:

var regex = /^[a-zA-Z]*$/;

Demo

and if you do not want to use Regex, then here is one approach:

function allowLetters(e, t) {
  try {
    if (window.event) {
      var charCode = window.event.keyCode;
    }
    else if (e) {
      var charCode = e.which;
    }
    else { return true; }
    return charCode > 64 && charCode < 91 || charCode > 96 && charCode < 123;
  }
  catch (err) {
    alert(err.Description);
  }
}

Here is one approach for the HTML5 template attribute:

<form> 
    <input type='text' pattern='[A-Za-z\\s]*'/> 
</form>
+6
source

I would look at regex for something like [A-Za-z]+.

This might be useful: (or any other RegExp guide online)

https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

+1
source

All Articles