Reputation: 331
I have a form validation script. Unless all conditions are met, the ambiguous function associated with form.onclick
returns false (form doesn't submit). I have another function which upon error will append an error message to the errorLog div.
function addError (msg) {
msg = document.createTextNode(msg);
br = document.createElement("br");
errorLog.append(msg);
errorLog.append(br);
alert("yes");
}
If an error is found, calling this function submits the form. The script doesnt even enter the function, it simply submits the data and refreshes. I realize there is an error in the function, but i cant seem to figure it out.
edit: more of my code
form.onsubmit = function ()
{
if (nameCheck(fname, lname))
return true;
return false;
};
function that checks if "name" field is valid:
function nameCheck (fname,lname)
{
if (("/\d/").test(fname) || ("/\d/").test(lname))
{
addError('Your name cannot contain numbers.');
valid = false;
}
}
Upvotes: 0
Views: 62
Reputation: 295
The simple way to do it is this:
form.onsubmit = function () {
if (("/\d/").test(fname) || ("/\d/").test(lname)) {
addError('Your name cannot contain numbers.');
return true;
} else { return false; }
};
and this way, you don't need the checkName()
part, but you still need the addError()
part.
Upvotes: 0
Reputation:
You're not stopping the form from submitting.
Use e.preventDefault()
to temporarily stop the form from submitting, then if the form is correct use this.submit()
to finish submitting the form
form.onsubmit = function (e) {
e.preventDefault();
if (nameCheck(fname, lname)) {
this.submit();
return true;
}
return false;
};
Also, nameCheck
will never resolve true, as it doesnt return anything. It should look like this
function nameCheck (fname,lname) {
if (("/\d/").test(fname) || ("/\d/").test(lname)) {
addError('Your name cannot contain numbers.');
return false;
}
return true;
}
Upvotes: 2