None
None

Reputation: 9247

Check if v-model is empty?

I want to prevent if user didnt enter anything. I tried like this but its not working:

 if(this.comment === ' '){
       return;
  }

This is my entire method:

 postComment: function(user_id,article_id) {
                if(this.comment === ' '){
                  return;
                }
                else{
                var article_comments = {
                  title: this.comment,
                  upovotes: this.article_comments.upovotes,
                  downvotes: this.article_comments.downvotes,
                  user_id : user_id,
                  article_id: article_id
                };

                  this.comments.push({
                      title: this.comment,
                      downvotes: 0,
                      upvotes: 0
                    })

                    this.$http.post('/blog/article/' + article_id + '/comment', article_comments).then(function(response){

                    },function(response){

                  });

                }
                this.comment = "";
              },

In view i have this:

  <div class="col-md-11 col-sm-11 col-xs-11">
     <textarea  class="comment_input" placeholder="Join the discussion..." v-model="comment" @keyup.enter="postComment({{$current_user->id}},{{ $article->id}})"></textarea>
 </div>

Upvotes: 3

Views: 7931

Answers (1)

Quasdunk
Quasdunk

Reputation: 15220

First off, you are checking for ' ', which is not a blank text but a whitespace. If you want to check for a blank text, it would be

if(this.comment === '')

or

if(this.comment.length == 0)

Second, you should trim the whitespace before and after the input:

if(this.comment.trim() === '')

Or, as of Vue 2.0+, you can use the trim input modifier directly within the markup:

<textarea v-model.trim="comment" ...>

And last but not least, you should listen for the keydown rather than keyup event so you get the input at the time you're pressing the key and not after the key already has modified the input by adding a new line. And since you want to handle this event yourself, you should prevent the default action:

<textarea @keydown.enter.prevent="postComment()" ...>

Upvotes: 5

Related Questions