Validation does not work in Mozilla, but works in Google Chrome

I have to face a problem while checking. It works in google chrome but not in Mozilla.

Like: I have a form where Name: ____ .

I want to check to prevent the user from writing a numeric value.

Inside 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 doesn't it work in Mozilla?

+4
source share
2 answers

This should fix:

 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 if brackets if already Boolean. If you do not need to return true or false , you basically said:

 if(true) return true; else return false; 

Firefox told me that "e is undefined" You will need to use the event object for this browser (as shown above)

preventDefault() not required. Returning false will prevent Firefox from entering a false key in the field.

+1
source

You forgot 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 script .

It is best to attach event listeners to the DOM elements when the window loads, and not through the html attributes, as it separates your HTML from your JavaScript. It also has the added advantage of choosing when you want to capture the event itself.
You can still capture window.event inside the function, if absolutely necessary for compatibility.


The " undefined " problem in Firefox comes from event , which is considered more as a keyword than a variable, so window.event === undefined , but event !== undefined , so if you want to save a thing as an attribute, you can do it like this
onkeypress="return checkerFunction1(window.event||event)"

+1
source

Source: https://habr.com/ru/post/1446951/


All Articles