Ankur
Ankur

Reputation: 12774

Form submits even after validation function throws Uncaught Exception

I have a form on whose validation function a line throws an uncaught exception, but instead of stopping the execution the browser submits the form

http://jsfiddle.net/yur4U/1/

 function validation(){
   var value = document.forms["myform"]['badInput'].value;//this line throws an exception
   return false;
 }​

<form name='myform' action ="" onsubmit="return validation()" method="POST">
    <input name='myInput' value="testing" type="text"/>
     <input value="submit" type="submit"/>
</form >

the code above provides one is a simple example , but i might be doing some calculations or conversions which might produce an Exception. One way to handle this is to enclose it in try catch

function validation(){
   var ret =true;
   try{
       var value = document.forms["myform"]['badInput'].value;
       ......//some condition to make ret=false
   } catch(e){
       ret = false
   }
   return ret;
 }​

But I am searching for a better way to do this? I think browser should be handling this by default, is this mentioned anywhere in the spec about how a browser should behave if onsubmit function throws an Exception?

Upvotes: 1

Views: 748

Answers (1)

pozs
pozs

Reputation: 36224

var value = document.forms["myform"]['badInput'].value;
//this line throws an exception

Because there is no "badInput" named element in your form. Although it is better to use form.elements["elementName"] or even better use a JS framework (like jQuery / dojo / etc.).

If you still need this line, you could check with typeof:

if (typeof document.forms["myform"].elements['badInput'] != "undefined")
   ...

Upvotes: 1

Related Questions