user1835080
user1835080

Reputation: 269

Validation is not working in Mozilla but working in Google Chrome

I am facing problem in validation. It is working in google chrome, but not in Mozilla.

Like: I have a form where Name: ____ .

I want to put a validation so that the user can't write a numeric value.

Inside the javascript:

function checkerFunction1(e)
{
    var charCode1=e.which || e.keyCode;
    if((charCode1 >= 65 && charCode1 <= 90) ||(charCode1 >= 97 && charCode1 <= 122) ||(charCode1==32 || charCode1==8 || charCode1==46))
        return true;
    return false;
}     

Inside the jsp page:

<input type="text" value="Name" onkeypress="return checkerFunction1(window.event)"/>

Why it is not working in Mozilla?

Upvotes: 4

Views: 2503

Answers (2)

Paul S.
Paul S.

Reputation: 66364

You have forgotten to call e.preventDefault().

function checkerFunction1(e) {
    e = e || window.event;
    var charCode1=e.which || e.keyCode;
    if(
        (charCode1 >= 65 && charCode1 <= 90)
        || (charCode1 >= 97 && charCode1 <= 122)
        || (charCode1==32 || charCode1==8 || charCode1==46)
    ) return true;
    return e.preventDefault(), false;
}

see this fiddle.

It is better practice to attach event listeners to DOM elements on window load rather than via html attributes as it separates your HTML from your JavaScript. It also has the added benefit of choosing when you want to capture the event itself.
You can still grab window.event inside the function if absolutely required for compatibility.


The "undefined problem" in Firefox comes from event being treated more like a keyword than a variable, so window.event === undefined but event !== undefined, therefore if you want to keep the thing as an attribute, you could do it like this
onkeypress="return checkerFunction1(window.event||event)"

Upvotes: 1

Cerbrus
Cerbrus

Reputation: 72947

This should fix it:

function checkerFunction1(e)
{
    e = e || window.event;
    var charCode1=e.which || e.keyCode;
    return ((charCode1 >= 65 && charCode1 <= 90) ||(charCode1 >= 97 && charCode1 <= 122) ||(charCode1==32 || charCode1==8 || charCode1==46))
} 

The condition in the if's brackets is a boolean already. The if is not needed when you want to return a true or false, you were basically saying:

if(true)
    return true;
else
    return false;

Firefox was telling me "e is undefined" You'll need to use the event object for that browser (as seen above)

preventDefault() is not needed. Returning false will prevent Firefox from entering a false key into the field.

Upvotes: 1

Related Questions