AFS
AFS

Reputation: 317

Regex to admit space on Javascript

I'm trying to validate a form field , i need this fields admitts only letters and spaces but if I write an space in the form the field is not validated,what is the regex which allows to write blank spaces??

function isCharacter(element, message){
    var alphaExp = /^[a-zA-Z]\s+$/;
    if(element.value.match(alphaExp)) {
        return true;
    } else {
        alert(message);
        return false;
    }
}

Upvotes: 0

Views: 422

Answers (4)

andre123
andre123

Reputation: 11

var alphaExp = /^[a-zA-Z]+$/;
var idLetters = ["a", "b", "m"]; 

var counter = 0;
var counter1 = 0;
var errors = "";

var numberonly = id.slice(0,-1);
var lettersonly = id.slice(-1);

Upvotes: 0

nu11p01n73R
nu11p01n73R

Reputation: 26667

You can force the first character to be aphabet, and then alphabet or spaces as

/^[a-zA-Z][a-zA-Z\s]+$/

This ensures that the input filed will not contains spaces alone

"asdf asdf".match(/^[a-zA-Z][a-zA-Z\s]+$/)
=> True

"   ".match(/^[a-zA-Z][a-zA-Z\s]+$/)
=> False

Upvotes: 2

cнŝdk
cнŝdk

Reputation: 32145

The problem is with your regex, you have to put the \s inside the [] to achieve it.

var alphaExp = /^[a-zA-Z\s]+$/;

Here's a DEMO.

Upvotes: 2

Ahosan Karim Asik
Ahosan Karim Asik

Reputation: 3299

Can use html5 pattern for easily handle

<input type="text" name="name" pattern="^[a-zA-Z\s]+$" />
<input type="submit" value="ok" name="ok" />

Upvotes: 0

Related Questions