Re: Empty input box
- From: RobG <rgqld@xxxxxxxxxxxx>
- Date: Mon, 24 Apr 2006 21:44:28 +1000
Paul Lautman wrote:
Hi y'all,
I found this function at http://www.devshed.com/c/a/JavaScript/Form-Validation-with-JavaScript/6/
// check to see if input is whitespace only or empty
function isEmpty(val)
{
if (val.match(/^s+$/) || val == "")
That regular expression will match a string consisting only of one or more 's' characters. It will return an array object of all the matches.
Otherwise, it will return null (which type-converts to boolean false).
If there are no characters at all, val=='' will return true.
So if you enter only one or more 's' characters or nothing at all, the if expression returns true.
[...]
When I tried it it didn't work, but I found that I could make it work by changing the regex to /^\s+$/
That will match a string consisting of one or more whitespace characters only (space, tab, and so on). The returned object type-converts to 'true'.
I then tried shortening it to:
function isEmpty(val)
{
return (val.match(/^s+$/) || val == "");
Now you are back to square one.
[...]
Can someone answer the following 2 questions for me:
1) I'm sure that the function worked for the author (Nariman K), so why did I need to add the escape character to get it to work?
Can't answer that, it should 'work' only as described above.
2) If the expression evaluates to true/false for the purposes of the if statement, why does it not return true/false reliably in the shortened form?
It doesn't do what you think it's doing. You probably want to see if the value is nothing or only whitespace, in which case you want to test if it contains any non-whitespace character:
function isEmpty(val)
{
return /\S/.test(val);
}
Note the additional backslash '\' before the 'S' character to let the regular expression know to use the special meaning of 'S' to match any non-whitespace character.
Incidentally, test() returns true or false which seems more appropriate for this test as no type-conversion is required.
--
Rob
.
- References:
- Empty input box
- From: Paul Lautman
- Empty input box
- Prev by Date: Re: Posting to 2 different files
- Next by Date: javascript and php
- Previous by thread: Re: Empty input box
- Next by thread: Re: Empty input box
- Index(es):
Relevant Pages
|