Tom Cruise Tom Cruise - 4 months ago 8
Javascript Question

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 ?

Answer

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/