PDA

View Full Version : Validate textboxes using event handler registration



papote
09-25-2014, 12:36 PM
I have a piece of JavaScript code that should validate that a username field is not empty or null and that a telephone field is in the correct format using event handler registration. It seems to be validating fine but if there is an error it still manages to submit.

HTML


<html>
<head>
<script type = "text/javascript" src = "js/validator.js" >
</script>
</head>

<body>

<form id = "decorForm" action = "">
<table border = "0">
<tr>
<th>Username: </th>
<td>
<input type = "text" id = "myUserName" size = "15" maxlength = "15"/>
</td>
</tr>

<tr>
<th>Telephone: </th>
<td>
<input type = "text" id = "telephone" name = "telephone" size = "15" maxlength = "13"/>
<br />
(999)999-9999
</td>
</tr>

<tr>
<td>
<input type = "submit" value = "Submit" />
</td>
<td>
<input type = "reset" value = "Reset" />
</td>
</tr>

</table>

</form>

<script type = "text/javascript" src = "js/validatorr.js" >
</script>

</body>
</html>


JAVASCRIPT (validator.js)



function chkUser() {
// Verifies that the UserName field is not empty.
var myUserName = document.getElementById("myUserName");
if (myUserName.value == "" || myUserName.value == null) {
alert ("Please enter a Username!");
return false;
} else {
return true;
}
}

function chkTelephone() {
// Verifies that the Telephone field value is in the correct format.
var tel = document.getElementById("telephone");
var pos = tel.value.search(/^\(\d{3}\)\d{3}-\d{4}$/);
if (pos != 0) {
alert ("Please enter telephone number in the following format: (999)999-9999");
return false;
} else {
return true;
}
}

function chkFields() {
// Verifes all fields and returns boolean to event handler
// The event handler function
if (chkUser() && chkTelephone()) {
return true;
} else {
return false;
}
}

JAVASCRIPT (validatorr.js)


//Register the event handlers for validator.js
document.getElementById("decorForm").onSubmit = chkFields;

I am trying to use this (http://biobio.loc.edu/chu/web/Courses/ITEC315/ch5/passwd.html) as an example.

jscheuer1
09-25-2014, 02:08 PM
There could also be other problems, but in javascript there is no event onSubmit. It's onsubmit. So before anything else can work or not work, this:


//Register the event handlers for validator.js
document.getElementById("decorForm").onSubmit = chkFields;

Needs to be:


//Register the event handlers for validator.js
document.getElementById("decorForm").onsubmit = chkFields;

papote
09-25-2014, 07:52 PM
I can't believe a little case insensitive was driving me nuts.
Thanks.