-1
$("#submit-signin-button").click(function() {
    if($.trim($("#foo").val()) === ""){
        $(".error-message-uname").show();
    }
    if($.trim($("#bar").val()) === ""){
        $(".error-message-bar").show();
    }

    return false;

Is it right way to do the validation? Because after submitting the correct form it does not post data to the URL.

1 Answer 1

2

The problem is that you are always returning false from this. You should only return false when the form should not be posted.

A very basic validation system based on your revised question. You have a variable initially set to true (all is fine) unless an error has occurred. Returning true on a form validation will cause the form to submit.

$("#submit-signin-button").click(function() {

  var isValid = true;

  if(!$.trim($("#foo").val()){
    $(".error-message-uname").show();
    isValid = false;
  }
  if(!$.trim($("#bar").val())){
    $(".error-message-bar").show();
    isValid = false;
  }

  return isValid;
}

For simple things, this is perfectly fine but there are some validation jQuery plugins (like this one) that you could use.

As a tip (so you know), an empty string is considered a falsey value in JavaScript. So you can replace $.trim($("#bar").val() === "" with !$.trim($("#bar").val().

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

1 Comment

what about if have another field to validate. I have update the question.

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.