-1

I am using XHTML, JSF and JavaScript to create a form, validate the information that has been submitted into their respective fields through the use of a onclick() in a h:commandButton.

I have managed to create a JS file that checks for empty fields and alerts the user if true, that works fine. I next wanted to try to make sure that the input matches the type defined in the tag using the typeMismatch property, in a function i've called Validity. Here is my code so far:

function Validity() {

var checkName=document.getElementById("formdiv:cardName");
var checkCard=document.getElementById("formdiv:cardnumber");
var checkExp=document.getElementById("formdiv:expDate");

var error="";

var inputChecks=[checkName, checkCard, checkExp];

for (i=0; i < inputChecks.length; i++){

    if(inputChecks[i].value.validity.typeMismatch){

        error= "Your fields dont match the required input type. E.g Card Number must be a number"
    }
}

document.getElementById("errorMessage").innerHTML=error; 

}

My problem lies on line 48 where i get a "Uncaught TypeError: Cannot read property 'typeMismatch' of undefined'. I have only been coding JS for a week so am relative new to it, so I'm sure it's down to how I'm declaring/ referencing something. I've have already checked w3schools and other sources all to no avail. So I'm hoping someone here will be able to help. Any suggestions would be greatly appreciated

CH1ND1T
  • 11
  • So do you have elements with `id="formdiv:cardName"` etc? Do these elements have `value`s? Do these `value`s have `validity`s? What's the value of `i` when the script crashes? – Mr Lister Aug 17 '16 at 15:11
  • Yes the elements relate to a h:inputText field within a form with id="formdiv", so when the onclick:"Validation()" is called the JS will get the values in the fields at that point. Example
    And the value of i is null as the script crashes upon evaluation of the if statement
    – CH1ND1T Aug 17 '16 at 16:08

1 Answers1

0

The only thing that we can discern from the code you've given and the error is that the 'validity' property hasn't been defined.

It's important to note the difference between null and undefinied in JavaScript.

Effectively the fact that it's undefined suggests that it's never been set. My guess would be that you have some problem where either the code that's setting the validity property isn't being executed, or it's behaving differently than what you'd expect.

If you add more information such as the rest of the code (JavaScript and XHTML) someone might be able to answer more specifically.

Truthy and Falsy values might also be useful to learn about as it's quite common for these sorts of things to unexpectely happen

Community
  • 1
  • 1
Brett
  • 843
  • 1
  • 7
  • 18