124697
124697

Reputation: 21893

How can I check if an input contains space characters only. I.e. one or more spaces only and no other characters

I need to detect on focusout if an input field contains only spaces. ie 1 or more spaces only and not any other characters?

At the moment it only detects if it contains 1 space only

$("#myInput").on("focusout",function(){
    if($(this).val() ==" "){ 
        //do work
    }
});

Upvotes: 0

Views: 2567

Answers (4)

Narasingha Padhi
Narasingha Padhi

Reputation: 25

if (yourstring.match(/^\S+([\s\xA0]| )+/, '')){

Upvotes: 0

Barmar
Barmar

Reputation: 780994

Use a regular expression:

if (/^\s+$/.test($(this).val())) { ...

Upvotes: 6

Adil
Adil

Reputation: 148120

Trim and compare length and check if length is zero.

$("#myInput").on("focusout",function(){
    if($(this).val().length && $.trim($(this).val()).length === 0){ 
        alert("string contains one or more spaces")
    }
});

Upvotes: 0

AMember
AMember

Reputation: 3057

I would go for the trim option.

Trim the input value then check if it is empty.

if (!String.prototype.trim) {
    String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};

    String.prototype.ltrim=function(){return this.replace(/^\s+/,'');};

    String.prototype.rtrim=function(){return this.replace(/\s+$/,'');};

    String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');};
}

Upvotes: 0

Related Questions