views:

319

answers:

2

My below mentioned code still submits form on special character in name field. Validation works but If I submit repeatedly it breaks and submits the form with special chars in name.

What could be the reason for this?

$("#fee").submit(function(){
   trimmedValue = $.trim($("#name").val());
   $("#name").val(trimmedValue);
   typevalue = $("input:radio[@name='type']:radio:checked").val();
   if(typevalue=="FLAT" && !isFloat($("#amount").val())) {
   alert("Amount should be number with proper decimal formatting");
   $("#amount").val("0.0");
    return false;
}
var noSpecialChars = /[^a-zA-Z0-9]/g;
if (noSpecialChars.test($("#name").val())) {
 alert("Please enter valid fee Name. Do not enter special characters"  );
 return false;
}

if(typevalue=="PERCENTAGE" && !isFloat($("#percentage").val())) {
   alert("percentage should be number with proper decimal formatting");
   $("#percentage").val("0.0");
    return false;
}
if(typevalue=="FLAT" && $("#amount").val()=="0.0") {
    return confirm("Do you really want the amount to be 0.0 ?");
}
if(typevalue=="PERCENTAGE" && $("#percentage").val()=="0.0") {
    return confirm("Do you really want the percentage to be 0.0 ?");
}

});

A: 

It appears that the interpreter is never reaching return false; on pressing repeatedly and is instead submitting the form to the href specified for the form.

If you have an href in your form tag, try removing it and inserting the property just before return is called.

Crimson
I dont have href attribute for form. I have added action as well as method attribute.
Ketan Khairnar
+3  A: 

In which browser(s) can you reproduce this?

I did it on Firefox 3.5.2, but couldn't reproduce it on IE 6.0. After exploring some more, I noticed that in this line ...

if (noSpecialChars.test($("#name").val())) {

... the call to .test() was returning true, then false, in an alternating pattern (in Firefox only) suggesting some problem with the RegExp. So I tried replacing the implicit creation of the RegExp like this:

    //var noSpecialChars = /[^a-zA-Z0-9]/g;        
    var noSpecialChars = new RegExp("[^a-zA-Z0-9]");

And that fixed the problem for me.

Jeff Sternal
thanks this fixed the issue. Would like to know how to debug in this scenarios.
Ketan Khairnar
No problem - in this case I debugged it in a pretty low-tech fashion, by adding a textarea element to the page and writing the result of noSpecialChars.test($("#name").val()) to that textarea. I also used Firebug a bit to discount some early hypotheses.
Jeff Sternal