0

This is my simple form. I want to validate both inputs if it has some value inserted and that value is not a spaces. How can I achieve such functionality before request gets submitted to server side? Thanks a lot!

<form:form method="post" action ="${addQueryOverride}">
                    <label>Enter query string and product list ID: </label>
                    <input maxlength="30" class="text span-1" name="queryOverride" id="queryOverrideId"/>
                    <input onkeypress="return isNumberKey(event)" maxlength="30" class="text span-1" name="productList" id="productListId"/>
                    <input type="submit" value="Add">
                </form:form>
3
  • you may trim the inputs val and check if value is not equal to Empty string Commented Oct 8, 2013 at 16:14
  • use $('#productListId').val() and validate Commented Oct 8, 2013 at 16:15
  • But how do I do that on button click? How I prevent execution forward if invalid input is detected? THanks Commented Oct 8, 2013 at 16:18

2 Answers 2

1
$(function() { // when page load
  $("form").on("submit",function(e) {
    if ($.trim($("#queryOverrideId").val()) == "") {
      alert("Please enter query");
      $("#queryOverrideId").focus();
      return false;
    }
    var id = $("#productListId").val();
    if ($.trim(id) == "" || isNaN(id)) {
      alert("Please enter product list");
      $("#productListId").focus();
      return false;
    }
  });
});
Sign up to request clarification or add additional context in comments.

Comments

1

On submit, iterate over each of the fields and run a check:

$("form input:text").each(function() {
    var isValid = this.value.length > 0 && this.value.indexOf(" ") == -1;
    return isValid; //if true, go to next element, if false, break each loop
});

Comments

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.