dlofrodloh
dlofrodloh

Reputation: 1744

How to validiate form onsubmit when form is submitted via a link instead of a button

I've got the following simple test to validate the input on the form when it is submitted by clicking the "submit" link. Unfortunately, it doesn't validate the form.

<form id="testform" action = "?blah" onsubmit="return validateForm()">
  <input type="text" name="testinput" >
  <a href="#" onclick="document.getElementById('testform').submit();">Submit</a>
</form>

<script>
function validateForm() {
    var x = document.forms["testform"]["testinput"].value;
    if (x == null || x == "") {
        alert("Field must be filled out");
        return false;
    }
}
</script>

If I replace submitting with a button instead of a link then it validates the form properly. But how can I ensure it validates when I am using a link to submit as in the above example?

Upvotes: 0

Views: 258

Answers (3)

Blauharley
Blauharley

Reputation: 4246

This works for me. It takes advantage of a variable and of an assigned method to testform:

<form id="testform" action = "?blah" onsubmit="return formValid">
  <input type="text" name="testinput" >
  <a href="#" onclick="document.getElementById('testform').onsubmit();">Submit</a>
</form>

<script>

var formValid = false;

document.getElementById('testform').onsubmit = function(){
    console.log('submit');
    formValid = validateForm();
};

function validateForm() {
    var x = document.forms["testform"]["testinput"].value;
    if (x == null || x == "") {
        alert("Field must be filled out");
        return false;
    }
}
</script>

Upvotes: 1

technophobia
technophobia

Reputation: 2629

Try creating a function that triggers the validation when clicking on the link.

Example:

<form id="testform" action = "?blah" onsubmit="return validateForm()">
  <input type="text" name="testinput" >
  <a href="#" onclick="return false; submitForm()">Submit</a>
</form>

<script>
function validateForm() {
    var x = document.forms["testform"]["testinput"].value;
    if (x == null || x == "") {
        alert("Field must be filled out");
        return false;
    }
}
function submitForm() {
    if (validateForm()) {
        document.getElementById('testform').submit();
    }
}
</script>

Note: I would highly recommend decoupling your JavaScript from your HTML, but that's outside the scope of your question.

Upvotes: 1

Anders Lind&#233;n
Anders Lind&#233;n

Reputation: 7303

Here comes a jQuery style way of doing it.

<form id="testform" action = "?blah" onsubmit="return validateForm()">
    <input type="text" name="testinput" />
  <a href="#" onclick="$('form').submit();">Submit</a>
</form>

<script type="text/javascript">
function validateForm() {
    if ($.trim($("[name=testinput]").val()) == "") {
        alert("Field must be filled out");
        return false;
    }
}
</script>

Upvotes: 1

Related Questions