Tom Cruise
Tom Cruise

Reputation: 69

Unable to validate properly in jquery

I'm validating an input from a user in jquery. If the input is empty, false is returned and jquery code doesn't run and if it contains some text the jquery code runs. Here is an example-

function sendm() {
    var valid;
    valid = sendmval();
    if (valid) {
        //jquery code
    }
}

function sendmval() {
    var valid = true;
    if (!$('#message').val()) {
        valid = false;
    } else {}
    return valid;
}

This works fine. However the problem occurs when user inputs blank spaces only and thus results in running of jquery code even on blank input. How can I prevent this ?

Upvotes: 1

Views: 84

Answers (2)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

Since spaces count as character so you have to use $.trim() of Jquery like below:-

if (!$.trim($('#message').val())) {
        valid = false;
}

For more reference:-

https://api.jquery.com/jQuery.trim/

Upvotes: 4

Iceman
Iceman

Reputation: 6145

Since space is also a character, simple use .trim() function of Javascript strings to remove blank space in the beginning and end. Then proceed with your check as usual.

Note: I have changed:

if (!$('#message').val())

to

if (!$('#message').val().trim())

See full working code test:

function sendm() {
  var valid;
  valid = sendmval();
  if (valid) {
    alert("valid & sendm");
  }
}

function sendmval() {
  var valid = true;
  if (!$('#message').val().trim()) {
    valid = false;
  } else {}
  return valid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="message">
<button onclick="sendm()">CHECK</button>

Upvotes: 3

Related Questions