0

I am trying to validate a text box, to have any character, but not empty.

This is my current code

condition = '\\d{9}';
condition = new RegExp(condition);
    if (condition.test(element.val())) {
             //some code
        }

But, i want it to allow all characters, but not empty, I have already tried .{50}, /./s and [\s\S] , But none seem to be working.

4

4 回答 4

2

It looks like you use jQuery. Try to pass value to $.trim to cut all non-space characters:

if ($.trim(element.val()).length > 0) {
    // ...
}

In case if you don't use jQuery, there is String.trim() method available. Check the compatibility information at MDN.

于 2013-02-12T12:26:52.737 回答
1

If it can be any character, but not empty, you could just test the length of the input's current value. E.g.

if (element.val().length > 0) {
    //some code
}

If you must use a regex then the following will work:

condition = /.+/;
于 2013-02-12T12:26:01.297 回答
1

Your regex matches only strings with 9 digits. For at least a single character, use .*[^\\s].* which ensures at least one non-space character.

于 2013-02-12T12:26:30.677 回答
0

Not sure if I understand the question:

condition = '^[\\s\\S]+$';
condition = new RegExp(condition);

if (condition.test(element.val())) {
    //some code
}

It will pass for any string that as at least one character, and fails for empty string. Notice that also whitespace are considered, so if element.val() is " " it will returns true. If you want to returns false in this case too, you have just to remove \\s from the string above.

于 2013-02-12T12:35:17.113 回答