Form validation isn't working when submitting it using Javascript

 I have a basic webform that calls a Javascript method after clicking on the submit button. The method applies some logic and when it's done, the form is submitted.

It seems that I can't force the user to fill up the form anymore, although I see the error flag appears for a split second, the form still submits even when it's empty. It ignores the 'required' attribute.

Form (snippet):


<form method='post' id='prechatForm' autocomplete="on">
* <input type="text" name='liveagent.prechat:ContactFirstName' class="form-control" id="firstName" placeholder="John" required="true" autofocus="true"></input>
* <input type="text" name='liveagent.prechat:ContactLastName' class="form-control" id="lastName" placeholder="Smith" required="true"></input>
<input type='submit' class="btn btn-default btn-lg btn-outline" value='Chat Now' id='prechat_submit' onclick="setName();checkIfCaseExists()" />
JS method:
[removed] function checkIfCaseExists() { some remote logic................... document.forms["prechatForm"].submit(); return true; }
set 'action' attribute to form:
(function() { function handlePageLoad() { var endpointMatcher = new RegExp("[\?\&]endpoint=([^&#]*)"); document.getElementById('prechatForm').setAttribute('action', decodeURIComponent(endpointMatcher.exec[removed].search)[1])); } if (window.addEventListener) { window.addEventListener('load', handlePageLoad, false); } else { window.attachEvent('onload', handlePageLoad, false); } })();

when I use the regular functionality of the submit button, i.e. without calling any method on the way and then submitting, the validation works fine.

Answered by Behailu

javascript.submit not working, this problem lies in the validate form method itself, specifically in the else block. You're returning false before the alert call. Swap the two calls around and you should see the alert message appear.

For clarity's sake, I would change the message in the alert box as it isn't directly relevant to the fields you're validating.

function validateForm() { var xa = document.forms["regform"]["password"].value; var xb = document.forms["regform"]["password2"].value; var xc = document.forms["regform"]["email"].value; var xd = document.forms["regform"]["email2"].value; if (xa == xb && xc == xd){ return true; } else { alert("Please enter a valid captcha code"); return false; } }

Your Answer


Parent Categories