Aoi M. Serizawa
Aoi M. Serizawa

Reputation: 483

regex with space and letters only?

I made a regular expression that only accepts letters. I'm not really good in regex, thats why I don't know how to include spaces in my regex.

My HTML:

<input id="input" />

My js / jQuery code:

$('#input').on('keyup', function() {
      var RegExpression = /^[a-zA-Z]*$/; 

      if (RegExpression.test($('#input').val())) {

      } 
      else {
          $('#input').val("");
      }
});​

Upvotes: 44

Views: 168723

Answers (6)

Pragnesh Chauhan
Pragnesh Chauhan

Reputation: 8476

use this expression

var RegExpression = /^[a-zA-Z\s]*$/;  

Update: 27-April-2023

function validate(){
  const regEx1 = /[^a-zA-Z\s]+/;
    input.value = input.value.replace(regEx1, '');
}
<input id="input" type="text" onkeyup="return validate();">

Upvotes: 100

aris
aris

Reputation: 597

this one works great for me

/[^a-zA-Z' ']/g

Upvotes: 1

Ali Raza
Ali Raza

Reputation: 720

regex expression:

var reg_name_lastname = /^[a-zA-Z\s]*$/;

Validation to the user_name input field

if(!reg_name_lastname.test($('#user_name').val())){ //
    alert("Correct your First Name: only letters and spaces.");
    valid = false;
}

Upvotes: 0

Jayant Muthekar
Jayant Muthekar

Reputation: 1

Allowed only characters & spaces. Ex : Jayant Lonari

if (!/^[a-zA-Z\s]+$/.test(NAME)) {
    //Throw Error
}

Upvotes: -1

Tats_innit
Tats_innit

Reputation: 34117

Try this demo please: http://jsfiddle.net/sgpw2/

Thanks Jan for spaces \s rest there is some good detail in this link:

http://www.jquery4u.com/syntax/jquery-basic-regex-selector-examples/#.UHKS5UIihlI

Hope it fits your need :)

code

 $(function() {

    $("#field").bind("keyup", function(event) {
        var regex = /^[a-zA-Z\s]+$/;
        if (regex.test($("#field").val())) {
            $('.validation').html('valid');
        } else {
            $('.validation').html("FAIL regex");
        }
    });
});​

Upvotes: 4

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123428

$('#input').on('keyup', function() {
     var RegExpression = /^[a-zA-Z\s]*$/;  
     ...

});

\s will allow the space

Upvotes: 10

Related Questions