1

I'm using jQuery so i wonder how can i show error message after i click submit button only if an input field is empty.

Below the code my simple form how to apply to it.

<form id="myid" name="myid" method="post" action="hook.php">

name : <input type="text" name="name" id="name">

age : <input type="text" name="age" id="age">

<input type="submit" id="submit" name="submit" value="Save" />

</form>

I would like to show error like this

enter image description here

Reham Fahmy
  • 4,937
  • 15
  • 50
  • 71

5 Answers5

6

As someone has already mentioned, you should probably look to use an external library for validation. That said, this seems like it might work (see JSFiddle):

var $form = $("#myid"),
    $errorMsg = $("<span class='error'>This field is required..!!</span>");

$("#submit").on("click", function () {
    // If any field is blank, we don't submit the form
    var toReturn = true;
    $("input", $form).each(function () {
        // If our field is blank
        if ($(this).val() == "") {
            // Add an error message
            if (!$(this).data("error")) {
                $(this).data("error", $errorMsg.clone().insertAfter($(this)));
            }
            toReturn = false;
        }
        // If the field is not blank
        else {
            // Remove the error message 
            if ($(this).data("error")) {
                $(this).data("error").remove();
                $(this).removeData("error");
            }
        }
    });
    return toReturn;
});
Ian Clark
  • 9,237
  • 4
  • 32
  • 49
1

You can use event.preventDefault to stop the default action happening. Then check your condition, display errors if the condition fails and submit the form if not.

$("#submit").click(function(event) {
  event.preventDefault();
  if($(this).val().length === 0) {
    // display some error  
  } else {
    $("#myid").submit();
  }
});
Dan Prince
  • 29,491
  • 13
  • 89
  • 120
1

Really I advice you to use some frameworks for form validation. Because that's the common task and it was already done 100000 times before. There are plenty of it, for example Parsley or Jquery plugin, but there are a lot of others which is simple and easily maintainable, just google 'javascript form validation'

Why is already implemented code better than custom in that case: 1) It already written, tested and working, 2) You almost never need only single validation, and really to validate form for several parameters could be a challenge and could lead to a big amount of validation code 3) framework is DRYer and a really a lot of other stuff.

Ph0en1x
  • 9,943
  • 8
  • 48
  • 97
0

I also advise you to use validation framework because you need more validation for different field. Use MooTools Floor this is most reliable framework for validation. MooTool Floor

Prateek
  • 6,785
  • 2
  • 24
  • 37
-1

You can use the HTML5 required='required' option in the input tag...

Sid
  • 381
  • 2
  • 12