4

I was wondering how I would write a regex expression which says 'and NO whitespaces'.I need to implement this into the following if statement, see below:

$('#postcode').blur(function(){
    var postcode = $(this), val = postcode.val();

    if((val.length >= 5) && (*******)){ 
       postcode.val(val.slice(0, -3)+' '+val.slice(-3)).css('border','1px solid #a5acb2'); 
    }else{ 
       $(this).css('border','1px solid red'); 
    }
});

Any help is greatly appreciated, Thanks

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Nasir
  • 4,785
  • 10
  • 35
  • 39

4 Answers4

4

Try this:

&& (!val.match(/\s/))

match return null if there are no spaces (or at least one space), so you can use it as a condition.

Kobi
  • 135,331
  • 41
  • 252
  • 292
  • 1
    If you really want to, you can combine the length check into the regex using `if(val.match(/^\S{5,}$/))` (note the upper-case S), but I'm not sure it's better. – Kobi Dec 01 '10 at 10:31
1
&& (val.indexOf(" ") == -1)

Note: Regex shouldn't be used if other options are readily available.

darioo
  • 46,442
  • 10
  • 75
  • 103
  • True, but `\s` also checks for tabs and newlines. Usually people refer to `" "` as "space" and the rest as "whitespace", but it is a better solution for normal spaces. – Kobi Dec 01 '10 at 10:26
  • Good point. If this is only a single-line edit control, `space` is the only reasonable whitespace. However, if it's a textarea, there can be tabs, and linebreaks, and whatnot (these can also be pasted into a text input field from clipboard). Regex is actually reasonable here, as it matches any kind of whitespace. – Piskvor left the building Dec 01 '10 at 10:27
  • @Kobi, @Piskvor: you are both correct. Combination of " ", tabs, newlines with all all their nice `\r`, `\n` variants can make whitespace matching problematic. In that case, regex is the best solution, but my answer is based on OP's question ;-) – darioo Dec 01 '10 at 10:31
1

Would cleaning the whitespaces before line 3 of your code help? (probably less intrusive)

Community
  • 1
  • 1
Ryan Fernandes
  • 8,238
  • 7
  • 36
  • 53
1

You can do both in the same regexp (guessing postcode is digits).

('1234567').match(/^\d{5,}$/) // ['1234567']
('1234').match(/^\d{5,}$/) // null
('12 34').match(/^\d{5,}$/) //null
('123 4567').match(/^\d{5,}$/) //null

so instead of:

if((val.length >= 5) && (*******)){
    //code
}

use:

if(val.match(/^\d{5,}$/)) {
    //code
}
fredrik
  • 17,537
  • 9
  • 51
  • 71
  • 1
    I've just posted something similar in a comment. You may want `\S` instead of `\d`, depending on possible values. – Kobi Dec 01 '10 at 10:33