2

I am running a client side validation javascript which will submit a form via an ajax post after validating the data. Here is the javascript:

$(".button").click(function() {

            $(".error").hide();

            var name = $(":input.name").val();
            if ((name == "") || (name.length < 4)){

                $("label#nameErr").show();
                $(":input.name").focus();
                return false;
            }

            var email = $(":input.email").val();
            if (email == "") {

                $("label#emailErr").show();
                $(":input.email").focus();
                return false;
            }


            var phone = $(":input.phone").val();
            if (phone == "") {

                $("label#phoneErr").show();
                $(":input.phone").focus();
                return false;
            }

            var comment = $("#comments").val();
            if ((!comment) || (comment > 100)) {

                $("label#commentErr").show();
                $("#comments").focus();
                alert("hello");
                return false;
            }

            var info = 'name:' + name + '&email:' + email + '&phone:' + phone + '&comment:' + comment;
            var ajaxurl = '<?php echo admin_url("admin-ajax.php"); ?>';
            alert(info);

            jQuery.ajax({

                type:"post",
                dataType:"json",
                url: myAjax.ajaxurl,
                data: {action: 'submit_data', info: info},
                success: function(response) {
                    if (response.type == "success") {

                        alert("success");
                    }
                    else {

                        alert("fail");
                    }
                }
            });

            $(":input").val('');
            return false;


        });

The four input fields are three text inputs for name, email and phone and then one textarea for the comments/queries section. The problem is that if I leave the textarea blank or enter over 100 characters the script does not go into the if ((!comment) || (comment > 100)) statement. I am wondering if there is a different value that gets assigned to a textarea when it is blank that is stopping the code from seeing it as empty ?

1
  • Hello! Don't forget to accept an answer - you even get 2 rep for it! Commented Apr 3, 2014 at 22:34

4 Answers 4

24

You need to check the length property of comment (also, you have a few extra parens. They won't break anything, but aren't needed).

if (!comment || comment.length > 100) {

What's currently happening is that you're trying to determine if a given string is less than a number, which is quite silly, so JS declares it false. Checking comment.length compares it to a number, which is what you wanted it to do.

!comment works because an empty string is falsy, though what you think is empty might not be (for instance, a string with a space is non-empty: ' '). Use .trim() to eliminate that pesky whitespace:

if (!comment.trim() && comment.length > 100)

(as a side note, none of the above requires jQuery, it's all JavaScript)

Sign up to request clarification or add additional context in comments.

8 Comments

Why doesn't it work if the OP leaves the field blank, though? "The problem is that if I leave the textarea blank or enter over 100 characters..."
i related to this in my answer, not handling Trim condition
!comment just handles case of undefined or null (null in some cases)
@OriRefael it also handles cases of empty strings, as I've explained.
@SomeKittensUx2666: String#trim is still missing for browsers in significant use in the wild.
|
2

You have two symptoms:

  1. Leaving the field blank doesn't trigger the condition, and

  2. Entering more than 100 characters doesn't trigger the condition.

The others have pointed out why #2 doesn't happen: You're doing comment > 100 where you need comment.length > 100.

The first is most likely because the field isn't completely blank, but rather has some whitespace in it. We can remove that whitespace with jQuery's $.trim (which works cross-browser, whereas .trim on strings doesn't work in IE8). So:

var comment = $.trim($("#comments").val()); // trim removes leading and trailing whitespace
if ((!comment) || (comment.length > 100)) { // Include .length

That's assuming you don't want to count leading and trailing whitespace.

Comments

-1
if ( comment == '' || comment.length > 100 ) {

10 Comments

But... it works. OP didn't use the .length property to check the length of the comment. (user I am replying to deleted their post)
@user2864740 So for you, comment > 100 and comment.length > 100 are the same? Wow...
@Shomz Ahh, yes. Missed that bit in the other change. Just rationally explain/expand the answer.
@Shomz: This is why it's important not just to dump updated code, but to say what you changed, and why. Also: The OP said it didn't work when they left the field blank; this doesn't address that at all.
@T.J.Crowder I know and I agree, but this was so straightforward I really thought no explanation was needed. And it does address the empty field.
|
-2

one reason that everyone here are making a mistake, if i provide an empty string which contains 100 empty spaces they return true.

the current and right way to check for empty string is

if (!comment && comment.trim().length > 100)

trim actually mean that empty spaces from the begining and end of the string are deleted.

3 Comments

String#trim is still missing on browsers in significant use in the wild.
Disagree, works on Opera, I.E, Firefox, Chrome and Avant, also on mobile browsers.
@ Ori: sigh IE8 is still in significant use in the wild (depending who you ask, between 6.2% and 21.4% here in April 2014). And it doesn't have String#trim.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.