I wonder why is the form still submitted instead of show the validation results. I have tried also having an onclick event at input type line but also no joy :-(
This is the form
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=iso-8859-1"/>
<title>Submit a runner time</title>
</head>
<body>
<script src="TMA02validationSubmitResultForm.js"></script>
<hr/>
<h1>Submit a runner time</h1>
<hr/>
Note: all fields marked '*' are mandatory.
<p/>
<form action="http://jdm423.tt284.open.ac.uk/uploadblock2/storedata.php" method="post" onsubmit="return validateForm()" id="submitrunnertime" name="submitrunnertime">
<table>
<div id="error"> </div>
<tr><td>Runner ID*</td>
<td><input type="text" onblur="validateRunnerId()" id="RunnerId" name="RunnerId" size="5" maxlength="5"/></td>
</tr>
<tr><td>Event ID*</td>
<td><input type="text" onblur="validateEventId()" name="EventId" id="EventId" size="5" maxlength="5"/></td>
</tr>
<tr><td>Date (YYYY-MM-DD)*</td>
<td><input type="text" onblur="validateDate()" name="Date" id="When" size="10" maxlength="10"/></td>
</tr>
<tr><td>Finish time (HH:MM:SS)*</td>
<td><input type="text" onblur="validateTime()" name="FinishTime" id="Time" size="8" maxlength="8"/></td>
</tr>
<tr><td>Position*</td>
<td><input type="text" onblur="validatePosition()" name="Position" id="Position" size="5" maxlength="5"/></td>
</tr>
<tr><td>Category ID*</td>
<td><input type="text" onblur="validateCategoryId()"name="CategoryId" id="CategoryId" size="2" maxlength="3"/></td>
</tr>
<tr><td>Age grade*</td>
<td><input type="text" onblur="validateAge()" name="AgeGrade" id="Age" size="5" maxlength="5"/></td>
</tr>
<tr><td>Personal best</td>
<td><input type="text" onblur="validatePB()" name="PB" id="PB" size="1" maxlength="1"/></td>
</tr>
</table>
<input type="submit" name="submitrunnertime" id="submitrunnertime" value="submit"/>
<hr/>
</form>
</body>
</html>
and the JS
function validateForm() {
return (validateRunnerId
&& validateEventId
&& validateDate
&& validateTime
&& validatePosition
&& validateCategoryId
&& validateAge
&& validatePB);
}
function validateRunnerId(ID) {
var ID = document.getElementById('RunnerId').value;
var legalEntry = /^\d{1,5}?$/;
if (ID.length == 0) {
RunnerId.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The RunnerId can\'t be empty";
return false;
}
else if (!legalEntry.test(ID)) {
RunnerId.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The RunnerId must be a number from 1 to 99999";
return false;
}
else {
RunnerId.style.background = 'White';
document.getElementById('error').innerHTML = "";
return true;
}
}
function validateEventId(ID) {
var ID = document.getElementById('EventId').value;
var legalEntry = /^\d{1,5}?$/;
if (ID.length == 0) {
EventId.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The EventId can\'t be empty";
return false;
}
else if (!legalEntry.test(ID)) {
EventId.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The EventId must be a number from 1 to 99999";
return false;
}
else {
EventId.style.background = 'White';
document.getElementById('error').innerHTML = "";
return true;
}
}
function validateDate(ymd) {
var ymd = document.getElementById('When').value;
var legalEntry = /^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/;
if (ymd.length == 0) {
When.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The date can\'t be empty";
return false;
}
else if (!legalEntry.test(ymd)) {
When.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The date must be in format YYYY-MM-DD";
return false;
}
else {
When.style.background = 'White';
document.getElementById('error').innerHTML = "";
return true;
}
}
function validateTime(tm) {
var tm = document.getElementById('Time').value;
var legalEntry = /^\d\d\:[0-5][0-9]\:[0-5][0-9]$/
if (tm.length == 0) {
Time.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The finish time can\'t be empty";
return false;
}
else if (!legalEntry.test(tm)) {
Time.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The finish time must be in format HH:MM:SS";
return false;
}
else {
Time.style.background = 'White';
document.getElementById('error').innerHTML = "";
return true;
}
}
function validatePosition(pos) {
var pos = document.getElementById('Position').value;
var legalEntry = /^\d{1,5}?$/
if (pos.length == 0) {
Position.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The position can\'t be empty";
return false;
}
else if (!legalEntry.test(pos)) {
Position.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The position must be a number from 1 to 99999";
return false;
}
else {
Position.style.background = 'White';
document.getElementById('error').innerHTML = "";
return true;
}
}
function validateCategoryId(ID) {
var ID = document.getElementById('CategoryId').value;
var legalEntry = /^\d\d?[0]?$/;
if (ID.length == 0) {
CategoryId.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The CategoryId can\'t be empty";
return false;
}
else if (!legalEntry.test(ID)) {
CategoryId.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The CategoryId must be a number from 1 to 100";
return false;
}
else {
CategoryId.style.background = 'White';
document.getElementById('error').innerHTML = "";
return true;
}
}
function validateAge(agrade) {
var agrade = document.getElementById('Age').value;
var legalEntry = /^\d\d?\,?\d?\d?$/;
if (agrade.length == 0) {
Age.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The age grade can\'t be empty";
return false;
}
else if (!legalEntry.test(agrade)) {
Age.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The age grade must be decimal number of maximum 2 integers and 2 decimals";
return false;
}
else {
Age.style.background = 'White';
document.getElementById('error').innerHTML = "";
return true;
}
}
function validatePB(pbest) {
var pbest = document.getElementById('PB').value;
var legalEntry = /^(0|1)$/;
if (pbest.length == 0) {
pbest.value = "0";
}
else if (!legalEntry.test(pbest)) {
PB.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The PB can only be 0 for false and 1 for true";
return false;
}
else {
PB.style.background = 'White';
document.getElementById('error').innerHTML = "";
return true;
}
}
Many thanks in advance for taking the time to help this rookie :)
In this code:
function validateForm() {
return (validateRunnerId
&& validateEventId
&& validateDate
&& validateTime
&& validatePosition
&& validateCategoryId
&& validateAge
&& validatePB);
}
...you're not calling your functions, you're just referring to them. And since a function reference is truthy, that condition is always true and the form is always valid.
To call a function, you put () after it. Assuming your functions don't need arguments, that would just be:
function validateForm() {
return (validateRunnerId()
&& validateEventId()
&& validateDate()
&& validateTime()
&& validatePosition()
&& validateCategoryId()
&& validateAge()
&& validatePB());
}
It's hard to tell, though, because a lot of your functions declare arguments but then also declare the same symbol as variables, which is odd to put it mildly.
Related
I have one html page with three number fields.
function checkLength_minlen(elem) {
if (elem.value == ''){
document.getElementById("msg1").innerHTML = 'Min 6 and Max 256';
document.getElementById("msg1").style.color = 'black';
document.getElementById("submit").disabled = true;
}
else if (elem.value < 6) {
document.getElementById("msg1").style.color = 'red';
document.getElementById("msg1").innerHTML="Min value is 6";
document.getElementById("submit").disabled = true;
}
else if (elem.value > 256) {
document.getElementById("msg1").style.color = 'red';
document.getElementById("msg1").innerHTML="Max value is 256";
document.getElementById("submit").disabled = true;
}
else {
document.getElementById("msg1").style.color = 'green';
document.getElementById("msg1").innerHTML="Min 6 and Max 256";
document.getElementById("submit").disabled = false;
}
}
function checkLength_expiry(elem) {
if (elem.value == ''){
document.getElementById("msg2").innerHTML = 'Min 2 and Max 1024';
document.getElementById("msg2").style.color = 'black';
document.getElementById("submit").disabled = true;
}
else if (elem.value < 2) {
document.getElementById("msg2").style.color = 'red';
document.getElementById("msg2").innerHTML="Min value is 2";
document.getElementById("submit").disabled = true;
}
else if (elem.value > 1024) {
document.getElementById("msg2").style.color = 'red';
document.getElementById("msg2").innerHTML="Max value is 1024";
document.getElementById("submit").disabled = true;
}
else {
document.getElementById("msg2").style.color = 'green';
document.getElementById("msg2").innerHTML="Min 2 and Max 1024";
document.getElementById("submit").disabled = false;
}
}
function checkLength_history(elem) {
if (elem.value == ''){
document.getElementById("msg3").innerHTML = 'Min 1 and Max 32';
document.getElementById("msg3").style.color = 'black';
document.getElementById("submit").disabled = true;
}
else if (elem.value < 1) {
document.getElementById("msg3").style.color = 'red';
document.getElementById("msg3").innerHTML="Min value is 1";
document.getElementById("submit").disabled = true;
}
else if (elem.value > 32) {
document.getElementById("msg3").style.color = 'red';
document.getElementById("msg3").innerHTML="Max value is 32";
document.getElementById("submit").disabled = true;
}
else {
document.getElementById("msg3").style.color = 'green';
document.getElementById("msg3").innerHTML="Min 1 and Max 32";
document.getElementById("submit").disabled = false;
}
}
<div id="Minlen">
<label class="heading">Minimum Length</label>
<input type="number" id="Minlen_text" min=6 max=256 onkeyup="checkLength_minlen(this)" value='8'> <span class="heading1" id="msg1"></span>
</div>
<div id="expiry">
<label class="heading">Expiry</label>
<input type="number" id="Expiry_text" min=2 max=1024 onkeyup="checkLength_expiry(this)" value='100'> <span class="heading1" id="msg2"></span>
</div>
<div id="history">
<label class="heading">History</label>
<input type="number" id="History_text" min=1 max=32 onkeyup="checkLength_history(this)" value='5'> <span class="heading1" id="msg3"></span>
</div>
<input type=submit class="commit" id="submit" value=Commit onclick="commit()">
Now my question is like the "Commit" button is getting disabled on wrong entry in the field one (Minlen) and when I switched to the second number field the "commit" button is getting enabled.
But I want the commit button to be disabled if any of the fields have out of range values.
I use three boolean variable to control validation of this three input. It's a very simple way to achieve your target. try this:
var isValidMinLen=true;
var isValidExpiry=true;
var isValidHistory=true;
function checkLength_minlen(elem) {
if (elem.value == ''){
document.getElementById("msg1").innerHTML = 'Min 6 and Max 256';
document.getElementById("msg1").style.color = 'black';
document.getElementById("btn").disabled = true;
isValidMinLen=false;
}
else if (elem.value < 6) {
document.getElementById("msg1").style.color = 'red';
document.getElementById("msg1").innerHTML="Min value is 6";
document.getElementById("btn").disabled = true;
isValidMinLen=false;
}
else if (elem.value > 256) {
document.getElementById("msg1").style.color = 'red';
document.getElementById("msg1").innerHTML="Max value is 256";
document.getElementById("btn").disabled = true;
isValidMinLen=false;
}
else {
debugger
document.getElementById("msg1").style.color = 'green';
document.getElementById("msg1").innerHTML="Min 6 and Max 256";
isValidMinLen=true;
checkButtonValidation();
}
}
function checkLength_expiry(elem) {
if (elem.value == ''){
document.getElementById("msg2").innerHTML = 'Min 2 and Max 1024';
document.getElementById("msg2").style.color = 'black';
document.getElementById("btn").disabled = true;
isValidExpiry=false;
}
else if (elem.value < 2) {
document.getElementById("msg2").style.color = 'red';
document.getElementById("msg2").innerHTML="Min value is 2";
document.getElementById("btn").disabled = true;
isValidExpiry=false;
}
else if (elem.value > 1024) {
document.getElementById("msg2").style.color = 'red';
document.getElementById("msg2").innerHTML="Max value is 1024";
document.getElementById("btn").disabled = true;
isValidExpiry=false;
}
else {
document.getElementById("msg2").style.color = 'green';
document.getElementById("msg2").innerHTML="Min 2 and Max 1024";
isValidExpiry=true;
checkButtonValidation();
}
}
function checkLength_history(elem) {
if (elem.value == ''){
document.getElementById("msg3").innerHTML = 'Min 1 and Max 32';
document.getElementById("msg3").style.color = 'black';
document.getElementById("btn").disabled = true;
isValidHistory=false;
}
else if (elem.value < 1) {
document.getElementById("msg3").style.color = 'red';
document.getElementById("msg3").innerHTML="Min value is 1";
document.getElementById("btn").disabled = true;
isValidHistory=false;
}
else if (elem.value > 32) {
document.getElementById("msg3").style.color = 'red';
document.getElementById("msg3").innerHTML="Max value is 32";
document.getElementById("btn").disabled = true;
isValidHistory=false;
}
else {
document.getElementById("msg3").style.color = 'green';
document.getElementById("msg3").innerHTML="Min 1 and Max 32";
isValidHistory=true;
checkButtonValidation();
}
}
function checkButtonValidation(){
debugger
if(isValidMinLen==false || isValidExpiry==false || isValidHistory==false){
document.getElementById("btn").disabled = true;
}else{
document.getElementById("btn").disabled = false;
}
}
<div id="Minlen">
<label class="heading">Minimum Length</label>
<input type="number" id="Minlen_text" min=6 max=256 onkeyup="checkLength_minlen(this)" value='8'> <span class="heading1" id="msg1"></span>
</div>
<div id="expiry">
<label class="heading">Expiry</label>
<input type="number" id="Expiry_text" min=2 max=1024 onkeyup="checkLength_expiry(this)" value='100'> <span class="heading1" id="msg2"></span>
</div>
<div id="history">
<label class="heading">History</label>
<input type="number" id="History_text" min=1 max=32 onkeyup="checkLength_history(this)" value='5'> <span class="heading1" id="msg3"></span>
</div>
<input type=submit class="commit" id="btn" value=Commit onclick="commit()">
Ok so my code is below. Once the calculate price button is clicked, I want it to display the results beneath the button. ie. number of cars = CarNumber, type of car = CarType and the price of the car = CarPrice. I know this is probably super easy to do but I just cant get it to work.
HTML:
<!DOCTYPE html>
<html>
<body>
<form name="Cars">
<h1>Car Sales</h1>
<p>Which type of car would you like (A, B or C)</p>
<input type="text" name="CarType"><br>
<p>how many cars would you like (1-100)</p>
<input type="text" name="CarNumber"><br>
<br>
<button onclick="return beginfunction()">Calculate Price</button>
<p id="message"></p>
<script src="car.js"> </script>
</form>
</body>
</font>
JavaScript:
function beginfunction() {
var CarType = document.forms["Cars"]["CarType"].value;
var CarNumber = document.forms["Cars"]["CarNumber"].value;
var CarPrice;
if ( !( CarType == 'A' || CarType == 'B' || CarType == 'C' ) ) {
CarTypeError = "Invalid Car Type";
document.getElementById("message").innerHTML = CarTypeError;
return false;
}
{
if (isNaN(CarNumber)) {
CarNumberError = "Invalid Quantity Entered";
document.getElementById('message').innerHTML = CarNumberError;
return false;
}
}
{
if (CarNumber >0 && CarNumber <10)
{
}
else
CarError = "Invalid";
document.getElementById('message').innerHTML = CarError;
return false;
}
{
if (CarType == 'A') {
CarPrice = 30;
} else if (CarType == 'B') {
CarPrice = 20;
} else if (CarType == 'C'){
CarPrice = 10;
}
}
}
The way that you use innerHTML is right, but there is some logic problems in your function, here is the refactored code:
function beginfunction() {
var CarType = document.forms["Cars"]["CarType"].value;
var CarNumber = document.forms["Cars"]["CarNumber"].value;
var CarPrice;
var message = "";
if ( !( CarType == 'A' || CarType == 'B' || CarType == 'C' ) ) {
message = "Invalid Car Type";
}else{
if (CarType == 'A') {
CarPrice = 30;
} else if (CarType == 'B') {
CarPrice = 20;
} else if (CarType == 'C'){
CarPrice = 10;
}
message = CarPrice;
}
if (isNaN(CarNumber)) {
message = "Invalid Quantity Entered";
}
if (CarNumber >0 && CarNumber <10)
{
}
else{
message = "Invalid";
}
document.getElementById('message').innerHTML = message;
return false;
}
Learning JS more in-depth of late, as I've not had to mess with it work. Trying to code some form validation, and it keeps "stopping" at the first input. Any advice is greatly appreciated. I have tried everything I can think of, read so many articles on form validation and nothing works. If anyone can point out my errors and "why" they're errors it'd be much appreciated. Here's my code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<script language="javascript" type="text/javascript">
function validateForm() {
var validFirst = document.forms["myForm"]["fname"].value;
if (validFirst == null || validFirst == "") {
document.getElementById("firstError").innerHTML = "Required Field";
document.getElementById("first").style.backgroundColor = "red";
return false;
}
else if (validFirst.length < 2) {
document.getElementById("firstError").innerHTML = "Response too short";
document.getElementById("first").style.backgroundColor = "red";
return false;
}
else if (validFirst !== null) {
document.getElementById("firstError").innerHTML = "";
document.getElementById("first").style.backgroundColor = "white";
return false;
}
var validLast = document.forms["myForm"]["lname"].value;
if (validLast == null || validLast == "") {
document.getElementById("lastError").innerHTML = "Required Field";
document.getElementById("last").style.backgroundColor = "red";
return false;
}
else if (validLast.length < 2) {
document.getElementById("lastError").innerHTML = "Response too short";
document.getElementById("last").style.backgroundColor = "red";
return false;
}
else if (validLast !== null) {
document.getElementById("lastError").innerHTML = "";
document.getElementById("last").style.backgroundColor = "white";
return false;
}
var validEmail = document.forms["myForm"]["email"].value;
if (validEmail == null || validEmail == "") {
document.getElementById("emailError").innerHTML = "Required Field";
document.getElementById("email").style.backgroundColor = "red";
return false;
}
else if (validEmail.length < 2) {
document.getElementById("emailError").innerHTML = "Response too short";
document.getElementById("email").style.backgroundColor = "red";
return false;
}
else if (validEmail !== null) {
document.getElementById("emailError").innerHTML = "";
document.getElementById("email").style.backgroundColor = "white";
return false;
}
var validPhone = document.forms["myForm"]["phone"].value;
if (validPhone == null || validPhone == "") {
document.getElementById("phoneError").innerHTML = "Required Field";
document.getElementById("phone").style.backgroundColor = "red";
return false;
}
else if (validEmail.length < 2) {
document.getElementById("phoneError").innerHTML = "Response too short";
document.getElementById("phone").style.backgroundColor = "red";
return false;
}
else if (validEmail !== null) {
document.getElementById("phoneError").innerHTML = "";
document.getElementById("phone").style.backgroundColor = "white";
return false;
}
}
</script>
<head>
<title>Form Validation</title>
<form name="myForm" action="" onsubmit="return validateForm()" method="post">
<table>
<tr>
<td>First Name</td>
<td><input type="text" id="first" name="fname" onchange="validFirst()"></td>
<td><span id="firstError"></span></td>
</tr>
<td>Last Name</td>
<td><input type="text" id="last" name="lname" onchange="validLast()"></td>
<td><span id="lastError"></span></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" id="email" name="email" onchange="validEmail()"></td>
<td><span id="emailError"></span></td>
</tr>
<tr>
<td>Phone</td>
<td><input type="text" id="phone" name="phone" onchange="validPhone()"></td>
<td><span id="phoneError"></span></td>
<tr>
<td><input type="submit" value="Submit"></td>
<td></td>
<td></td>
</tr>
</table>
In the last else statement in each section, you're returning the form field to its "non-error" state and then returning false, causing the validation function to exit.
The solution is to remove this last return false; in each group of if/else if blocks:
if (validFirst == null || validFirst == "") {
document.getElementById("firstError").innerHTML = "Required Field";
document.getElementById("first").style.backgroundColor = "red";
return false;
}
else if (validFirst.length < 2) {
document.getElementById("firstError").innerHTML = "Response too short";
document.getElementById("first").style.backgroundColor = "red";
return false;
}
else if (validFirst !== null) {
document.getElementById("firstError").innerHTML = "";
document.getElementById("first").style.backgroundColor = "white";
// return false; /**** this is causing your validation function to terminate ****/
}
https://jsfiddle.net/mblase75/75rcwv8k/
Fixed! thanks for the help, everyone!
function validateForm() {
var validFirst = document.forms["myForm"]["fname"].value;
if (validFirst == null || validFirst == "") {
document.getElementById("firstError").innerHTML = "Required Field";
document.getElementById("first").style.backgroundColor = "red";
}
else if (validFirst.length < 2) {
document.getElementById("firstError").innerHTML = "Response too short";
document.getElementById("first").style.backgroundColor = "red";
}
else if (validFirst !== null) {
document.getElementById("firstError").innerHTML = "";
document.getElementById("first").style.backgroundColor = "white";
}
var validLast = document.forms["myForm"]["lname"].value;
if (validLast == null || validLast == "") {
document.getElementById("lastError").innerHTML = "Required Field";
document.getElementById("last").style.backgroundColor = "red";
}
else if (validLast.length < 2) {
document.getElementById("lastError").innerHTML = "Response too short";
document.getElementById("last").style.backgroundColor = "red";
}
else if (validLast !== null) {
document.getElementById("lastError").innerHTML = "";
document.getElementById("last").style.backgroundColor = "white";
}
var validEmail = document.forms["myForm"]["email"].value;
if (validEmail == null || validEmail == "") {
document.getElementById("emailError").innerHTML = "Required Field";
document.getElementById("email").style.backgroundColor = "red";
}
else if (validEmail.length < 2) {
document.getElementById("emailError").innerHTML = "Response too short";
document.getElementById("email").style.backgroundColor = "red";
}
else if (validEmail !== null) {
document.getElementById("emailError").innerHTML = "";
document.getElementById("email").style.backgroundColor = "white";
}
var validPhone = document.forms["myForm"]["phone"].value;
if (validPhone == null || validPhone == "") {
document.getElementById("phoneError").innerHTML = "Required Field";
document.getElementById("phone").style.backgroundColor = "red";
}
else if (validEmail.length < 2) {
document.getElementById("phoneError").innerHTML = "Response too short";
document.getElementById("phone").style.backgroundColor = "red";
}
else if (validEmail !== null) {
document.getElementById("phoneError").innerHTML = "";
document.getElementById("phone").style.backgroundColor = "white";
}
return false;
}
</script>
<head>
<title>Form Validation</title>
</head>
<body>
<form name="myForm" action="" onsubmit="return validateForm()" method="post">
<table>
<tr>
<td>First Name</td>
<td><input type="text" id="first" name="fname" onchange="validFirst()"></td>
<td><span id="firstError"></span></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" id="last" name="lname" onchange="validLast()"></td>
<td><span id="lastError"></span></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" id="email" name="email" onchange="validEmail()"></td>
<td><span id="emailError"></span></td>
</tr>
<tr>
<td>Phone</td>
<td><input type="text" id="phone" name="phone" onchange="validPhone()"></td>
<td><span id="phoneError"></span></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>
function validate() {
if(document.myForm.name.value =="" ){
alert("Enter a name");
document.myForm.name.focus();
return false;
}
This is what I've written it for an empty string, now i need it to accept only letters?
If you want only letters - so from a to z, lower case or upper case, excluding everything else (numbers, blank spaces, symbols), you can modify your function like this:
function validate() {
if (document.myForm.name.value == "") {
alert("Enter a name");
document.myForm.name.focus();
return false;
}
if (!/^[a-zA-Z]*$/g.test(document.myForm.name.value)) {
alert("Invalid characters");
document.myForm.name.focus();
return false;
}
}
function alphaOnly(event) {
var key = event.keyCode;
return ((key >= 65 && key <= 90) || key == 8);
};
or
function lettersOnly(evt) {
evt = (evt) ? evt : event;
var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
((evt.which) ? evt.which : 0));
if (charCode > 31 && (charCode < 65 || charCode > 90) &&
(charCode < 97 || charCode > 122)) {
alert("Enter letters only.");
return false;
}
return true;
}
Try this:
var alphaExp = /^[a-zA-Z]+$/;
if(document.myForm.name.match(alphaExp))
{
//Your logice will be here.
}
else{
alert("Please enter only alphabets");
}
Thanks.
Use onkeyup on the text box and check the keycode of the key pressed, if its between 65 and 90, allow else empty the text box.
dep and clg alphabets validation is not working
var selectedRow = null;
function validateform() {
var table = document.getElementById("mytable");
var rowCount = table.rows.length;
console.log(rowCount);
var x = document.forms["myform"]["usrname"].value;
if (x == "") {
alert("name must be filled out");
return false;
}
var y = document.forms["myform"]["usremail"].value;
if (y == "") {
alert("email must be filled out");
return false;
}
var mail = /[^#]+#[a-zA-Z]+\.[a-zA-Z]{2,6}/
if (mail.test(y)) {
//alert("email must be a valid format");
//return false ;
} else {
alert("not a mail id")
return false;
}
var z = document.forms["myform"]["usrage"].value;
if (z == "") {
alert("age must be filled out");
return false;
}
if (isNaN(z) || z < 1 || z > 100) {
alert("The age must be a number between 1 and 100");
return false;
}
var a = document.forms["myform"]["usrdpt"].value;
if (a == "") {
alert("Dept must be filled out");
return false;
}
var dept = "`##$%^&*()+=-[]\\\';,./{}|\":<>?~_";
if (dept.match(a)) {
alert("special charachers found");
return false;
}
var b = document.forms["myform"]["usrclg"].value;
if (b == "") {
alert("College must be filled out");
return false;
}
console.log(table);
var row = table.insertRow(rowCount);
row.setAttribute('id', rowCount);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
var cell5 = row.insertCell(5);
var cell6 = row.insertCell(6);
var cell7 = row.insertCell(7);
cell0.innerHTML = rowCount;
cell1.innerHTML = x;
cell2.innerHTML = y;
cell3.innerHTML = z;
cell4.innerHTML = a;
cell5.innerHTML = b;
cell6.innerHTML = '<Button type="button" onclick=onEdit("' + x + '","' + y + '","' + z + '","' + a + '","' + b + '","' + rowCount + '")>Edit</BUTTON>';
cell7.innerHTML = '<Button type="button" onclick=deletefunction(' + rowCount + ')>Delete</BUTTON>';
}
function emptyfunction() {
document.getElementById("usrname").value = "";
document.getElementById("usremail").value = "";
document.getElementById("usrage").value = "";
document.getElementById("usrdpt").value = "";
document.getElementById("usrclg").value = "";
}
function onEdit(x, y, z, a, b, rowCount) {
selectedRow = rowCount;
console.log(selectedRow);
document.forms["myform"]["usrname"].value = x;
document.forms["myform"]["usremail"].value = y;
document.forms["myform"]["usrage"].value = z;
document.forms["myform"]["usrdpt"].value = a;
document.forms["myform"]["usrclg"].value = b;
document.getElementById('Add').style.display = 'none';
document.getElementById('update').style.display = 'block';
}
function deletefunction(rowCount) {
document.getElementById("mytable").deleteRow(rowCount);
}
function onUpdatefunction() {
var row = document.getElementById(selectedRow);
console.log(row);
var x = document.forms["myform"]["usrname"].value;
if (x == "") {
alert("name must be filled out");
document.myForm.x.focus();
return false;
}
var y = document.forms["myform"]["usremail"].value;
if (y == "") {
alert("email must be filled out");
document.myForm.y.focus();
return false;
}
var mail = /[^#]+#[a-zA-Z]+\.[a-zA-Z]{2,6}/
if (mail.test(y)) {
//alert("email must be a valid format");
//return false ;
} else {
alert("not a mail id");
return false;
}
var z = document.forms["myform"]["usrage"].value;
if (z == "") {
alert("age must be filled out");
document.myForm.z.focus();
return false;
}
if (isNaN(z) || z < 1 || z > 100) {
alert("The age must be a number between 1 and 100");
return false;
}
var a = document.forms["myform"]["usrdpt"].value;
if (a == "") {
alert("Dept must be filled out");
return false;
}
var letters = /^[A-Za-z]+$/;
if (a.test(letters)) {
//Your logice will be here.
} else {
alert("Please enter only alphabets");
return false;
}
var b = document.forms["myform"]["usrclg"].value;
if (b == "") {
alert("College must be filled out");
return false;
}
var letters = /^[A-Za-z]+$/;
if (b.test(letters)) {
//Your logice will be here.
} else {
alert("Please enter only alphabets");
return false;
}
row.cells[1].innerHTML = x;
row.cells[2].innerHTML = y;
row.cells[3].innerHTML = z;
row.cells[4].innerHTML = a;
row.cells[5].innerHTML = b;
}
<html>
<head>
</head>
<body>
<form name="myform">
<h1>
<center> Admission form </center>
</h1>
<center>
<tr>
<td>Name :</td>
<td><input type="text" name="usrname" PlaceHolder="Enter Your First Name" required></td>
</tr>
<tr>
<td> Email ID :</td>
<td><input type="text" name="usremail" PlaceHolder="Enter Your email address" pattern="[^#]+#[a-zA-Z]+\.[a-zA-Z]{2,6}" required></td>
</tr>
<tr>
<td>Age :</td>
<td><input type="number" name="usrage" PlaceHolder="Enter Your Age" required></td>
</tr>
<tr>
<td>Dept :</td>
<td><input type="text" name="usrdpt" PlaceHolder="Enter Dept"></td>
</tr>
<tr>
<td>College :</td>
<td><input type="text" name="usrclg" PlaceHolder="Enter college"></td>
</tr>
</center>
<center>
<br>
<br>
<tr>
<td>
<Button type="button" onclick="validateform()" id="Add">Add</button>
</td>
<td>
<Button type="button" onclick="onUpdatefunction()" style="display:none;" id="update">update</button>
</td>
<td><button type="reset">Reset</button></td>
</tr>
</center>
<br><br>
<center>
<table id="mytable" border="1">
<tr>
<th>SNO</th>
<th>Name</th>
<th>Email ID</th>
<th>Age</th>
<th>Dept</th>
<th>College</th>
</tr>
</center>
</table>
</form>
</body>
</html>
resolved my javascript issue. Sorry it was mainly my fault as i copied and pasted my code instead of rewriting it out again. Strange thing is that it doesn't seem to pass the variables from the form to the process page as i have echo'd the SQL statement back out. This form did work previously to the java script all i added in was Post Code: for each row and even after deleting the javascript it still doesn't work :S
Sorry deadline tomorrow and im panicing.
<script type="text/javascript">
function checkForm()
{
var username = document.getElementById('username').value;
if(username.length < 5)
{
alert("Username is to short");
return false;
}
else if (username.length<16)
{
alert("Username is to long");
return false;
}
var firstName = document.getElementById('firstName').value;
if(firstName.length <3)
{
alert("Forname is to short");
return false;
}
var lastName = document.getElementById('lastName').value;
if (lastName.length <3)
{
alert("Surname is to short");
return false;
}
var address = document.getElementById('address').value;
if (address.length <8)
{
alert("Address is to short");
return false;
}
var town = document.getElementById('town').value;
if (town.length <3)
{
alert ("Town is to short");
return false;
}
var postCode = document.getElementById('postCode').value;
if (postCode.length <6)
{
alert ("Invalid Post Code");
return false;
}
else if (postCode.length>8)
{
alert("Invalid Post Code");
return false;
}
var cardType = document.getElementById('cardType').value;
if (cardType.length <3)
{
alert ("Please enter a valid card type");
return false;
}
var password = document.getElementById('password').value;
if (password.length <6)
{
alert ("You password must be between 6-12 characters");
return false;
}
else if(password.length>12)
{
alert ("Your password must be between 6-12 characters");
return false;
}
else
{
return true;
}
}
function checkUsername()
{
var username = document.getElementById('username').value;
var element = document.getElementById('username1');
if(username.length < 5)
{
element.innerHTML = "Username is to short";
element.style.color = "red";
}
else if (username.length >16)
{
element.innerHTML = "Username is to long";
element.style.color = "red";
}
else
{
element.innerHTML = "Username";
element.style.color = "green";
}
}
function checkFname()
{
var firstName = document.getElementById('firstName').value;
var element = document.getElementById('firstname1');
if(firstName.length < 3)
{
element.innerHTML = "Forname is to short";
element.style.color = "red";
}
else
{
element.innerHTML = "Forname";
element.style.color = "green";
}
}
function checkLname()
{
var lastName = document.getElementById('lastName').value;
var element = document.getElementById('surname1');
if(lastName.length < 3)
{
element.innerHTML = "Surname is to short";
element.style.color = "red";
}
else
{
element.innerHTML = "Surname";
element.style.color = "green";
}
}
function checkAddress()
{
var address = document.getElementById('address').value;
var element = document.getElementById('address1');
if(address.length < 8)
{
element.innerHTML = "Address is to short";
element.style.color = "red";
}
else
{
element.innerHTML = "Address";
element.style.color = "green";
}
}
function checkTown()
{
var town = document.getElementById('town').value;
var element = document.getElementById('town1');
if(town.length < 3)
{
element.innerHTML = "Town is to short";
element.style.color = "red";
}
else
{
element.innerHTML = "Town";
element.style.color = "green";
}
}
function checkPostCode()
{
var postCode = document.getElementById('postCode').value;
var element = document.getElementById('postcode1');
if(postCode.length < 6)
{
element.innerHTML = "Post code is to short";
element.style.color = "red";
}
else if (postCode.length>8)
{
element.innerHTML = "Post Code To Long";
element.style.color = "red";
}
else
{
element.innerHTML = "Post Code";
element.style.color = "green";
}
}
function checkCard()
{
var cardType = document.getElementById('cardType').value;
var element = document.getElementById('card1');
if(cardType.length < 3)
{
element.innerHTML = "Card is to short";
element.style.color = "red";
}
else
{
element.innerHTML = "Card Type";
element.style.color = "green";
}
}
function checkPassword()
{
var password = document.getElementById('password').value;
var element = document.getElementById('password1');
if(password.length < 6)
{
element.innerHTML = "Password is to short";
element.style.color = "red";
}
else if (password.length>16)
{
element.innerHTML = "Password is to long";
element.style.color = "red";
}
else
{
element.innerHTML = "Password";
element.style.color = "green";
}
}
</script>
<p><b><h3>Welcome User Please Register</h3></b></p>
<form action="registerUserProcess.php" id="registerUserForm" method="post" name="registerUserForm" >
<table>
<tr><td><label id="username1">Username:</label></td><td><input id="username" type="text" size="16" onBlur='checkUsername();'/></td></tr>
<tr><td><label id="firstname1">Forename:</label></td><td><input id="firstName" type="text" size="20" onBlur="checkFname();" /></td></tr>
<tr><td><label id="surname1">Surname:</label></td><td><input id="lastName" type="text" size="30" onBlur="checkLname();" /></td></tr>
<tr><td><label id="address1">Address:</label></td><td><input id="address" type="text" size="50" onBlur="checkAddress();" /></td></tr>
<tr><td></td><td><input id="address2" type="text" size="50" onBlur="" /></td></tr>
<tr><td><label id="town1">Town:</label></td><td><input id="town" type="text" size="50" onBlur="checkTown();" /></td></tr>
<tr><td><label id="postcode1">Post Code:</label></td><td> <input type="text" id="postCode" size="8" onBlur="checkPostCode();" /></td></tr>
<tr><td><label id="contact1">Contact No:</label></td><td> <input type="number" id="contact" size="12" onBlur="checkContactNo();" /></td></tr>
<tr><td>Card Number:</td><td><input type="number" id="cardNo1" size="4" /> - <input type="number" id="cardNo2" size="4" /> - <input type="number" id="cardNo3" size="4" /> - <input type="number" id="cardNo4" size="4" /></td></tr>
<tr><td><label id="card1">Card Type</label></td><td> <input type="text" id="cardType" size="8" onBlur="checkCard();" /></td></tr>
<tr><td>Email Address:</td><td><input id="emailAddress" type="text" size="50" /></td></tr>
<tr><td><label id="password1">Password:</label></td><td><input id="password" type="password" size="16" onBlur="checkPassword();" /></td></tr>
<tr><td><label id="terms1">Accept Terms & Conditions:</label></td><td><input type="checkbox" id="termsConditions" value="yes" onBlur="checkTerms();" /></td></tr>
<tr><td><input type="reset" id="resetForm" value="Reset" id="resetForm" /></td><td><input type="submit" id="submitUser" value="Submit" id="submitUser" onSubmit='return checkForm();' /></td></tr>
</table>
</form>
As others said, check your syntax. In checkform(), it should be
else if (username.length > 16)) instead of < 16
and in checkUsername() you spelled length wrong.
But your main problem is in your returns. In checkform() you should only put return true at the end when everything has been validated, or else the function just exit after the first validation.
You could also refactor all of this. You've got plenty of function that do almost the same thing. If you make one function that take minimum characters, maximum characters and the control to validate in parameters, you could do all of your code in 20 to 30 lines.
Plus, it seems like you copy-pasted some of your functions without changing the name of the variables or the targeted control. In fact, you assign Username as a variable in every function, but change the name in the condition, meaning you use an unassign variable.
Function: checkForm():
You need to change the second else if to:
else if (username.length<16)) needs to be > 16.
--
Function: checkUsername():
You have incorrectly spelled length. Change it to:
else if (username.length>16)
This is too much code for one question, but I noticed a few things in the first function:
else if (username.length<16) // This should probably be username.length > 16
{
alert("Username is to long");
return false;
}
if (isNAN(contact)) // this should probably be !isNaN(contact)
{
return true;
}
You misspelled length in the following: username.lenght>16
This is the reason your too long isn't working.
function checkUsername()
{
var username = document.getElementById('username').value;
var element = document.getElementById('username1');
if(username.length < 5)
{
element.innerHTML = "Username is to short";
element.style.color = "red";
}
else if (username.lenght>16)
{
element.innerHTML = "Username is to long";
element.style.color = "red";
}
else
{
element.style.color = "green";
}
}