Reputation: 5
Trying to learn JavaScript, makin decent progress I guess, but I'm stuck at validating a form, tried to see if anybody has the same problem, search didn't turn anything up. So would you please help me?
var minlength = 6;
var pwlength = document.getElementById('psswrd');
var invalid = " ";
function validate() {
if (pwlength.length < minlength && pwlength == invalid) {
alert("Password not valid");
else {
alert("Password okay!");
}
}
submitbtn.onClick = validate();
Upvotes: 0
Views: 85
Reputation: 177786
document.forms[0].submitbtn
document.getElementById("submitbtn")
or
document.getElementsByName("submitbtn")[0]
will work depending on how you name or ID the button HOWEVER do not assign onclick handlers to submit buttons, instead assign submit handler to the formI have taken the trim from here and I assume the form has ID="form1"
window.onload=function()
document.getElementById("form1").onsubmit = validate;
}
if(typeof String.prototype.trim !== 'function') { // let's help older IEs
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
function validate() {
var minlength = 6;
var pw = document.getElementById('psswrd');
if (pw.value.length < minlength || pw.value.trim() == "") {
alert("Password not valid");
pw.focus();
return false;
}
return true; // allow submission
}
Upvotes: 1
Reputation: 10057
You have a few problems here.
1) pwlength.length
won't get you very far. pwlength
is equal to an html object, not the value of an html object. Change the actual variable to the following and you should get the correct results:
var pwlength = document.getElementById('psswrd').value;
2) Before the else
part of your if ... else
statement, you need to end the if
statement by closing it with a curly bracket (}
). Change that part to the following:
} else {
3) Your validation to check and see if the length == invalid
is odd. Double check that and get rid of it.
4) Your onclick event needs to look something like this:
submitbtn.onclick = function(){ validate() };
Notice: lowercase event keyword and function() { ... };
wrapped around the function you want to run.
Upvotes: 0
Reputation: 1
var minlength = 6;
var pwlength = document.getElementById('psswrd');
var invalid = " ";
function validate() {
if (pwlength.length < minlength && pwlength == invalid) {
alert("Password not valid");
}
else {
alert("Password okay!");
}
}
Upvotes: 0