Ketan Khairnar
Ketan Khairnar

Reputation: 1630

JQuery form gets submitted even validation is returning false

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 ?");
}

});

Upvotes: 2

Views: 763

Answers (2)

Jeff Sternal
Jeff Sternal

Reputation: 48675

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.

Upvotes: 3

KJ Saxena
KJ Saxena

Reputation: 21848

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.

Upvotes: 0

Related Questions