Tom Cruise Tom Cruise - 1 year ago 46
Javascript Question

Unable to validate properly in jquery

I'm validating an input from a user in

. If the input is empty, false is returned and
code doesn't run and if it contains some text the
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
code even on blank input. How can I prevent this ?

Answer Source

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

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

For more reference:-