Form Validations in Javascript

Advertisement

I can not seem to understand why my code did not give me an error or success message when I clicked the submit button. I'm just trying to validate strings in html to make sure they're not null, not too big, and so on.

The developer tools and Lint online did not give me any error. I hope you can report any code I have written.

javscript:

 function submit() { var firstName = document.getElementById("fn"); var lastName = document.getElementById("ln"); var email = document.getElementById("email"); var emailR = document.getElementById("emailR"); var userName = document.getElementById("un"); var password = document.getElementById("pass"); var passwordR = document.getElementById("passR"); var error = ""; var letters = /^[a-zA-Z]+$/; var postal = document.getElementById("pc"); var code = /^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$/; if (firstName === null || firstName.length > 15 || !firstName.value.match(letters)) { error += "Please enter a valid first name."; } if (lastName === null || lastName.length > 15 || !lastName.value.match(letters)) { error += " Please enter a valid last name"; } var ei = email.value.lastIndexOf('@'); var dot = email.value.lastIndexOf('.'); if (email === null || email.length < 7 || ei == -1 || dot == -1 || dot < ei + 2) { error += " Please enter a valid email address"; } if (emailR != email) { error += " Your email addresses did not match"; } if (postal === null || !postal.length == 7 || !postal.value.match(code)) { error += "Postal code must follow Canadian standard. Eg \"N3H 1M1\" "; } if (userName === null || userName.length > 15) { error += " Please enter a valid username (must be less than 15 characters)"; } if (password === null || password.length > 15) { error += "please enter a valid password (must be less than 15 characters)"; } if (passwordR != password) { error += "your passwords do not match"; } if (error === "") { document.getElementById("test").innerHTML = "Thank you for signing up!"; } else if (error !== "") { document.getElementById("test").innerHTML = error; } } 

thank you,
Javanoob

The answer

document.getElementById gives you the HTMLEly complete object. To get the value, use the .value property. Example:

var email = document.getElementById("email").value;

(assuming that the HTML element with id = "email" is a text entry)