I am new to javascript and I am attempting to create a simple form validation. When I hit the submit button nothing happens. I have been looking at examples for a while and I cannot seem to figure out where I am going wrong. Any suggestions:
HTML:
<form name="myForm" class="appnitro" onsubmit="return validateForm()" action="mysql_connection.php" method="post">
<div class="form_description">
<h2>Patient Record</h2>
<p></p>
</div>
<ul>
<li id="li_1">
<label class="description" for="element_1"> Name</label>
<span>
<td width="68%"><input size="15" maxlength="30" class="input" type="text" name="Fname" id="Fname"></td>
<label>First</label>
</span>
<span>
<td width="68%"><input size="15" maxlength="30" class="input" type="text" name="Lname" id="Lname"></td>
<label>Last</label>
</span>
<li class="buttons">
<label class="description" for="element_1"> Gender</label>
<span>
<tr>
<select name="Gender">
</tr>
</span>
<option value="Select">Select</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<li class="buttons">
<label class="description" for="element_3"> Age</label>
<span>
<tr>
<select name="Age">
</tr>
</span>
<script type="text/javascript">
listAge()
</script>
</select>
<li class="buttons">
<label class="description" for="element_3"> Phone Number</label>
<span>
<td width="68%"><input size="25" maxlength="50" class="input" type="text" name="Phone" id="Phone"></td>
</span>
<li class="buttons">
<label class="description" for="element_3"> Email ID</label>
<span>
<td width="68%"><input size="25" maxlength="50" class="input" type="text" name="Email" id="Email"></td>
</span>
<li class="buttons">
<label class="description" for="element_3"> Address</label>
<span>
<td><textarea cols="25" rows="3" class="input" name="Address" id="Address"></textarea></td>
</span>
<li class="buttons">
<label class="description" for="element_3"> Reason For Visit</label>
<span>
<td><textarea cols="25" rows="3" class="input" name="Reason" id="Reason"></textarea></td>
</span>
<li class="buttons">
<label class="description" for="element_3"> Attending Doctor</label>
<span>
<td width="68%"><input size="25" maxlength="50" class="input" type="text" name="Doctor" id="Doctor"></td>
</span>
<li class="buttons">
<input type="submit" value="Submit" />
<input type="reset" value="Reset">
</li>
</ul>
</form>
Javascript:
<script>
function validateForm() {
var Fname = document.forms["myForm"]["Fname"].value;
var Lname = document.forms["myForm"]["Lname"].value;
var Phone = document.forms["myForm"]["Phone"].value;
var Address = document.forms["myForm"]["Address"].value;
var Reason = document.forms["myForm"]["Reason"].value;
var Doctor = document.forms["myForm"]["Doctor"].value;
var email = document.forms["myForm"]["email"].value;
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (Fname == null || Fname == "") {
alert("First name must be filled out");
return false;
}
if (Lname == null || Lname == "") {
alert("Last name must be filled out");
return false;
}
if (Phone == null || Phone == "") {
alert("Phone Number must be filled out");
return false;
}
if (Address == null || Address == "") {
alert("Address must be filled out");
return false;
}
if (Reason == null || Reason == "") {
alert("Reason for Visit must be filled out");
return false;
}
if (Doctor == null || Doctor == "") {
alert("Attending Doctor must be filled out");
return false;
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
return false;
}
}
function listAge() {
var i = 1;
for (i = 1; i <= 100; i++) {
document.write("<option value=" + i + ">" + i + "</option>");
}
}
</script>
Your HTML is hideously invalid. Odds are that the browser is trying to perform error recovery and doing things like moving the <form> element outside the table (assuming there is a table, it doesn't show up in your code but you have table data cells in it) so that the submit button is no longer inside it and does not try to submit the form. (This is a known problem with trying to interleave forms a table rows).
Use a validator to find your errors then fix them.
#Quentin is right, you need to clean your HTML code and javascript code.
But you have an error in your Javascript. You need to write a capital E for the Email field. It is case sensitive.
Try with this :
var email = document.forms["myForm"]["Email"].value;
Why not directly use the ID attribute of the element as if you put an ID inside any element it is always preferred to keep it unique. So you can use document.getElementById("ID").value; to get the value of an individual element. Like this :
var firstName = document.getElementById("firstNameTextBox").value;
if(firstName == ''){
message.innerHTML = "First Name is required";
}
I have a demo that you should try.
Demo
Add this JavaScript code and it should word
function validateForm() {
var Fname = document.forms["myForm"]["Fname"].value;
var Lname = document.forms["myForm"]["Lname"].value;
if (Fname == null || Fname == "") {
alert("First name must be filled out");
return false;
}
if (Lname == null || Lname == "") {
alert("Last name must be filled out");
return false;
}
if (Phone == null || Phone == "") {
alert("Phone Number must be filled out");
return false;
}
if (Address == null || Address == "") {
alert("Address must be filled out");
return false;
}
if (Reason == null || Reason == "") {
alert("Reason for Visit must be filled out");
return false;
}
if (Doctor == null || Doctor == "") {
alert("Attending Doctor must be filled out");
return false;
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
return false;
}
}
function listAge() {
var i = 1;
for (i = 1; i <= 100; i++) {
document.write("<option value=" + i + ">" + i + "</option>");
}
}
I believe the problem is that you try to take some values from fields that not exists at least from the code that you provided! Just copy the code above and it should work for sure!
Related
<!DOCTYPE html>
<html>
<body>
<div class="needContent">
<label for="Password">Password</label>
<span class="red-star">∗</span>
<input type="password" name="Password" id="Password" required="required" onkeyup="starShow()" pattern="^(?=.*\[a-z\])(?=.*\[A-Z\])(?=.*\d)\[a-zA-Z\d\]{8,}$" onchange="check()">
</div>
<div class="needContent">
<label for="Retype_Password">Retype Password</label>
<span class="red-star">∗</span>
<input type="password" name="Retype_Password" id="Retype_Password" pattern="^(?=.*\[a-z\])(?=.*\[A-Z\])(?=.*\d)\[a-zA-Z\d\]{8,}$" required="required" onkeyup="starShow()" onchange="check()">
<p id="status"></p>
<div id="phoneNumber" class="needContent">
<label for="Phone_Number" >Phone Number</label>
<span class="red-star">∗</span>
<input type="tel" name="Phone_Number" id="Phone_Number"
required="required" onchange="Error()" placeholder="999-999-9999"
onkeyup="starShow()" >
<p id="showEorror"></p>
</div>
</div>
<script>
function Error() {
var phn = document.getElementById("Phone_Number").value;
if(phn[3]!="-" && phn[7] != "-" ) {
document.getElementById("showEorror").innerHTML="<span>X</span> The area code of phone number 999-999-9999 can't be all zeros.";
}else if(phn[0] == 0 || phn[1] == 0 && phn[2] == 0){
document.getElementById("showEorror").innerHTML="<span>X</span> The area code of phone number 999-999-9999 can't be all zeros.";
} else {
document.getElementById("showEorrr").style.display = "none";
}
}
function check() {
var pass1 = document.getElementById("Password").value;
var pass2 = document.getElementById("Retype_Password").value;
if (pass1 != "" && pass2 != "") {
if (pass1 != pass2) {
document.getElementById("status").innerHTML = "<span>X</span> Doesn't Match.";
}
}
}
</script>
</body>
</html>
So I am working on my school project and I am trying to display the error "Doesn't Match" same as the one for the phone but I don't know what I am doing wrong. I have attached a screen shot of my output.
You're not resetting the #status text after the password gets properly entered. Try this instead:
if (pass1 != "" && pass2 != "") {
if (pass1 != pass2) {
document.getElementById("status").innerHTML = "<span>X</span> Doesn't Match.";
} else document.getElementById("status").textContent = 'ok';
}
For the phone section, you have a typo or two: "showEorror" vs "showEorrr", which means that, again, the error text does not go away. I recommend using showError or showPhoneError instead.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
How to print error message under respective input field if left empty and error message must be removed when filled, how to proceed further i have not used javascript for validation earlier.
script code
function validateForm() {
var a = document.forms["student_reg"]["name"].value;
if (a == null || a == "") {
alert("Name must be filled out");
return false;
}
var b = document.forms["student_reg"]["email"].value;
if (b == null || b == "") {
alert("Email must be filled out");
return false;
}
var c = document.forms["student_reg"]["username"].value;
if (c == null || c == "") {
alert("Username must be filled out");
return false;
}
var d = document.forms["student_reg"]["password"].value;
if (d == null || d == "") {
alert("Password must be filled out");
return false;
}
var e = document.forms["student_reg"]["roll_no"].value;
if (e == null || e == "") {
alert("Roll no must be filled out");
return false;
}
}
html code is here
<body>
Login
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="" >
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="" >
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="" >
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="" >
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="" >
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
</body>
You can try this code:
It will check errors and returns at last after displaying all error messages if any.
function validateForm() {
var error = 0;
var a = document.forms["student_reg"]["name"].value;
document.getElementById('name_error').innerHTML = '';
if (a == null || a == "") {
// alert("Name must be filled out");
error++;
document.getElementById('name_error').innerHTML = 'Name must be filled out';
}
var b = document.forms["student_reg"]["email"].value;
document.getElementById('email_error').innerHTML = '';
if (b == null || b == "") {
// alert("Email must be filled out");
error++;
document.getElementById('email_error').innerHTML = 'Email must be filled out';
}
var c = document.forms["student_reg"]["username"].value;
document.getElementById('username_error').innerHTML = '';
if (c == null || c == "") {
// alert("Username must be filled out");
error++;
document.getElementById('username_error').innerHTML = 'Username must be filled out';
}
var d = document.forms["student_reg"]["password"].value;
document.getElementById('password_error').innerHTML = '';
if (d == null || d == "") {
// alert("Password must be filled out");
error++;
document.getElementById('password_error').innerHTML = 'Password must be filled out';
}
var e = document.forms["student_reg"]["roll_no"].value;
document.getElementById('roll_no_error').innerHTML = '';
if (e == null || e == "") {
// alert("Roll no must be filled out");
error++;
document.getElementById('roll_no_error').innerHTML = 'Roll no must be filled out';
}
if(error>0) {
return false;
}
return true;
}
Keep all the name attributes in array and validate in loop. As your ID is related to name attribute, concatenate the name with _error to get the ID of the error placeholder.
function validateForm() {
var names = ['name', 'email', 'username', 'password', 'roll_no'];
var errorCount = 0;
names.forEach(function(el) {
var val = document.forms["student_reg"][el].value;
if (val == null || val == "") {
document.getElementById(el + '_error').textContent = el.toUpperCase().replace('_', ' ') + " must be filled out";
++errorCount;
}
});
if (errorCount) return false;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
You can iterate through all elements of the form student_reg to validate email and required and print error message under respective input field if no value was set:
const validateForm = () => {
const form = document.forms['student_reg'],
inputs = [...form.getElementsByTagName('input')],
errors = [...form.getElementsByClassName('error')],
regex = /\S+#\S+\.\S+/,
setErrorMsg = (str, msg) => `${str.replace('_', ' ')} ${msg}`
let countErrors = 0
inputs.forEach((input, index) => {
// clear all errors
(errors[index] || '').innerHTML = ''
// validate email
if (input.name === 'email' && !regex.test(input.value)) {
errors[index].innerText = setErrorMsg(input.name, 'should be valid')
countErrors++
}
// validate required
if (!input.value) {
errors[index].innerText = setErrorMsg(input.name, 'field is required')
countErrors++
}
})
return countErrors === 0
}
p {
font-size: 13px;
margin: 4px 0 0;
}
.error {
font-size: 12px;
padding: 6px 0 4px;
color: red;
display: block
}
.error:first-letter {
text-transform: uppercase
}
button {
margin-top: 8px;
font-size: 16px;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"></span>
<button>Submit</button>
</form>
simple form It hold the Span for the Error msg.The span Id is very important here.you need to make color for errors using css
<form id="loginform" name="loginform" action="" method="post">
<label>Name</label>
<input type="text" name="username" />
<p></p>
<span id="usernameError"></span>
<p></p>
<label>Pwd</label>
<input type="password" name="password" />
<p></p>
<span id="passwordError"></span>
<p></p>
<input type="submit" value="Submit" />
</form>
script
<script type="application/javascript">
window.onload = function(){
function handleinput(){
if(document.loginform.username.value == ""){
document.getElementById("usernameError").innerHTML = "You must enter a username";
return false;
}
if(document.loginform.password.value == ""){
document.getElementById("passwordError").innerHTML = "You must enter a password";
return false;
}
}
document.getElementById("loginform").onsubmit = handleinput;
}
</script>
I have a script here that is supposed to run when triggered. However, it will only work if the variable passwd is not used in my if else statements.
NEWLY UPDATED JS:
function validateForm() {
var name = document.forms["myForm"]["name"].value;
var phone = document.forms["myForm"]["phone"].value;
var email = document.forms["myForm"]["email"].value;
var add = document.forms["myForm"]["address"].value;
var passwd = document.forms["myForm"]["password"].value;
var matchesCount = email.split("#").length - 1;
var matchesCount2 = email.split(".").length - 1;
var error = "";
if (!name || !phone || !email || !add || !passwd) {
error+="All must be filled out \n"
if(phone.search(/^[0-9]*$/) == -1 || phone.length != 8){
error+="- Phone number can only contain digits \n";}
if(passwd.search(/^[0-9a-zA-Z]*$/) == -1){
error+="- Password needs to be alphanumeric \n";
}
if(passwd.length <8 || passwd.length > 16){
error+="- Password contain only 8-16 digits \n";
}
if(matchesCount > 1 || matchesCount2 < 1){
error+="- Please enter a valid email \n";
}
alert(error);
return false;
}
}
HTML
<div id="newaccount">
<table id="tablenewuser">
<form name="myForm" action="ControllerServlet" onsubmit="return validateForm()" method="post">
<tr>
<td class="newusertd">Name:<span class="price">*</span></td>
<td class="newusertd"><input style="color: black;" type="text" name="name" class="Btn"></td>
</tr>
<tr>
<td class="newusertd">Contact Number:<span class="price">*</span></td>
<td class="newusertd"><input style="color: black;" type="text" name="phone" placeholder="98989898"class="Btn"></td>
</tr>
<tr>
<td class="newusertd">Email:<span class="price">*<br></span></td>
<td class="newusertd"><input style="color: black;" type="text" name="email" placeholder="xxx#hello.com" class="Btn"></td>
</tr>
<tr>
<td class="newusertd">Address:<span class="price">*</span></td>
<td class="newusertd"><input style="color: black;" type="text" name="address" class="Btn"></td>
</tr>
<tr>
<td class="newusertd">Password:<span class="price">*</span><br>(8-16 Characters with<br>one UPPERCASE & numbers)</td>
<td class="newusertd"><input style="color: black;" type="password" name="password" class="Btn">
</tr>
<tr>
<td class="newusertd"></td>
<td class="newusertd">
<input style="color: black;" type="submit" value="Create Account" class="Btn"/></td>
</tr>
</form>
</table>
</div>
(Sorry for the mess!)
EDIT: The script works but the the password is not working as it should be. Please see the comments
Quick glance shows at least 2 problems with that area:
passwd could be null and pass through the outer if condition. Attempting length on it would cause an error
You may want to wrap the inner conditionals in an else block
if (name == null || name == "" || phone == null || phone == "" || email == null || email == "" || add == null || add == ""
|| passwd == null || passwd == "") {
error+="All must be filled out \n";
} else {
// other conditions
}
if (error) alert(error);
In JS, it's passwd.length not length()
You should use the JS console to verify what errors are appearing.
I see the problem, .length is a property, not a method. Your length check should be:
if (passwd.length >= 8 && passwd.length <= 16) {
error += "- Only 8-16 digits \n";
}
One more note, foo == null || foo == "" can be simplified to !foo as null and "" are both falsy values in JS.
Im not expert but i recommend you evaluate mail field with regex (/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/) and i created a separated function for validate each of the values in the form for add a text error, then another validation who evaluate if all the fiels pass the evaluation, like yours but i made it liek that: if(validateName(nameVar) && validateEmail(emailVar) this is all the code that i made, that validate a correct form mail, a name with alphabetical form and phone without null value:
function validateName(nameVar) {
var nameReg = /^[a-zA-Z'.\s]{1,40}$/;
return nameReg.test(nameVar);
}
function validateEmail(emailVar) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test(emailVar);
}
function email() {
var nameVar = $('#name').val();
var emailVar = $('#email').val();
var phoneVar = $('#phone').val();
var messageVar = $('#message').val();
if(!validateName(nameVar) ) {
console.log("dentro");
$('#nameError').text("Por favor ingresa un nombre valido");
}else{
$('#nameError').text("");
}
if(!validateEmail(emailVar) || emailVar == "") {
$('#emailError').text("Por favor ingresa un correo valido");
}else{
$('#emailError').text("");
}
if(phoneVar == "") {
$('#phoneError').text("Por favor ingresa un número telefonico");
}else{
$('#phoneError').text("");
}
if(validateName(nameVar) && validateEmail(emailVar) && emailVar != "" && phoneVar != ""){
var data = {};
data.name = nameVar;
data.email = emailVar;
data.phone = phoneVar;
data.message = messageVar;
//here your validate code with array of values ready for doing something
}
};
and this is the html code:
<h4 class="title-yellow contacto" id="title-yellow">Envianos un mensaje</h4>
<div class="row"> </div>
<div class="row">
<div class="col-md-6 form-group">
<input class="form-control" id="name" name="nombre" placeholder="Nombre" type="text" required >
</div>
<div class="col-md-6 form-group">
<input class="form-control" id="email" name="email" placeholder="Email" type="email" required >
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<input class="form-control" id="phone" name="telefono" placeholder="Teléfono" type="tel" required >
</div>
</div>
<textarea class="form-control" id="message" name="mensaje" placeholder="Mensaje" rows="4">
</textarea>
<br>
<div class="row">
<div class="col-md-12 form-group">
<button class="email nohover pull-right" id="mail" onclick="email()">ENVIAR</button>
<p id="demo"></p>
<div id="nameError"></div>
<div id="emailError"></div>
<div id="phoneError"></div>
<div id="ajaxMessage"></div>
</div>
</div>
I have a form which has four fields, when the all the fields are empty and submit button is clicked- it should alert "Please select at least one value".
When I enter the value in any of the fields the form should get submitted. I tried the following code but it's not working
function validatefleid() {
var computername = document.myform.computername.value;
var monitorname = document.myform.monitorname.value;
var tvname = document.myform.tvname.value;
var laptopname = document.myform.laptopname.value;
var cellphonename = document.myform.cellphonename.value;
if ((computername == null || computername == "") || (monitorname == null || monitorname == "") || (tvname == null || tvname == "") || (laptopname == null || laptopname == "") || (cellphonename == null || cellphonename == "")) {
alert("Please atleast one value");
return false;
}
}
<form name="myform" onsubmit="return validatefleid()">
computer
<input type="text" class="form-control inpt-bx-txtclr-home" name="computername" id="computerid" placeholder="000">monitor
<input type="text" class="form-control inpt-bx-txtclr-home" name="monitorname" id="monitorid" placeholder="000">tv
<input type="text" class="form-control inpt-bx-txtclr-home" name="tvname" id="tvid" placeholder="000">laptop
<input type="text" class="form-control inpt-bx-txtclr-home" name="laptopname" id="laptopid" placeholder="000">cellphone
<input type="text" class="form-control inpt-bx-txtclr-home" name="cellphonename" id="cellphoneid" placeholder="000">
<button type="submit">Calculate</button>
</form>
It is possible by iterating through all of the inputs within the form, and look for at least one input with value that's different than ''. Check the demo:
$(function(){
var $form = $('#myform');
$form.submit(function(){
var valid = false;
$('input', $form).each(function(){
if($(this).val() != ''){
valid = true;
}
});
if (!valid) {
alert("Please atleast one value");
}
return valid;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" name="myform">
computer<input type="text" class="form-control inpt-bx-txtclr-home" name="computername" id="computerid" placeholder="000">
monitor<input type="text" class="form-control inpt-bx-txtclr-home" name="monitorname" id="monitorid" placeholder="000">
tv<input type="text" class="form-control inpt-bx-txtclr-home" name="tvname" id="tvid" placeholder="000">
laptop<input type="text" class="form-control inpt-bx-txtclr-home" name="laptopname" id="laptopid" placeholder="000">
cellphone<input type="text" class="form-control inpt-bx-txtclr-home" name="cellphonename" id="cellphoneid" placeholder="000">
<button type="submit" >Calculate</button>
</form>
Without jQuery :
https://jsfiddle.net/uL28jsf9/
<script type="text/javascript">
function validatefleid()
{
var allFieldsNames = ['computername', 'monitorname', 'tvname', 'laptopname', 'cellphonename'];
var checkIfFieldEmpty function(fieldName) {
var fieldValue = document.myform[fieldName].value;
return fieldValue === "" || fieldValue === null
}
var allFieldsEmpty = allFieldsNames.every(checkIfFieldEmpty);
if (allFieldsEmpty) {
alert("Please atleast one value");
return false;
}
else {
alert("I'm ok with that !")
}
}
</script>
oops i have got the answer
I have a form which as four fields when the all the fields are empty and submit button is clicked it should alert as "please select atleast one value" when i entry the value in any of the one fields the form should get submitted i have tries the following code but its not working
<script type="text/javascript">
function validatefleid()
{
var computername=document.myform.computername.value;
var monitorname=document.myform.monitorname.value;
var tvname=document.myform.tvname.value;
var laptopname=document.myform.laptopname.value;
var cellphonename=document.myform.cellphonename.value;
if((computername==null || computername=="") && (monitorname==null || monitorname=="") && (tvname==null || tvname=="") && (laptopname==null || laptopname=="") && (cellphonename==null || cellphonename==""))
{
alert("Please atleast one value");
return false;
}
}
</script>
<form name="myform" onsubmit="return validatefleid()">
computer<input type="text" class="form-control inpt-bx-txtclr-home" name="computername" id="computerid" placeholder="000">
monitor<input type="text" class="form-control inpt-bx-txtclr-home" name="monitorname" id="monitorid" placeholder="000">
tv<input type="text" class="form-control inpt-bx-txtclr-home" name="tvname" id="tvid" placeholder="000">
laptop<input type="text" class="form-control inpt-bx-txtclr-home" name="laptopname" id="laptopid" placeholder="000">
cellphone<input type="text" class="form-control inpt-bx-txtclr-home" name="cellphonename" id="cellphoneid" placeholder="000">
<button type="submit" >Calculate</button>
</form>
here is a complete cross-browser working version of validatefleid function.
function validatefleid(){
var inputIds = ['computerid','monitorid','tvid','laptopid','cellphoneid'];
var hasEnteredAnyValue = false;
for(var i=0;i<inputIds.length;i++){
hasEnteredAnyValue = document.getElementById(inputIds[i]).value;
if(hasEnteredAnyValue)break;
}
if(!hasEnteredAnyValue)
{
alert("Please atleast one value");
return false;
}
}
I am using php mysql for user registration. I have added javascript validation to check if any field is blank or not. But the form validation is not working. the form is
<?php
include("header.php");
include ("includes/mainmenu.php");
?>
<!--Javasript Validation File Import -->
<script type="text/javascript" src="js/validation.js"></script>
<script type="text/javascript" src="js/formreg.js"></script>
<script type="text/javascript" language="JavaScript">
function HidePart(d) { document.getElementById(d).style.display = "none"; }
function ShowPart(d) { document.getElementById(d).style.display = "block"; }
function CheckboxChecked(b,d)
{
if(b) { ShowPart(d); }
else { HidePart(d); }
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!--<link rel="stylesheet" type="text/css" href="styles/styles.css" />-->
<link href="styles/form.css" rel="stylesheet" type="text/css">
<link href="styles/structure.css" rel="stylesheet">
<link href="styles/bootstrap.css" rel="stylesheet">
</head>
<body onLoad="document.registration.userid.focus();">
<br>
<div id="container" class="ltr">
<header id="header" class="info">
<h2>User Registration</h2>
</header>
<form action="insert.php" method="post" name="regForm" onSubmit="return valide()">
<ul>
<li id="foli0" class="notranslate">
<label class="desc" id="title0" for="Field0">Name</label>
<span><input id="fname" type="text" name="fname" class="field text1 fn" size="50"/></span><span>Please Enter Your full Name</span>
</li>
<li id="foli0" class="notranslate">
<label class="desc" id="title0" for="Field0">Username</label>
<span><input id="Field0" type="text" name="usernamename" class="field text1 fn" size="50" /></span>
</li>
<li id="foli0" class="notranslate">
<label class="desc" id="title0" for="group">Educational Background</label></td>
<span><select id="Field0" class="field text1 fn" name="background" size="0">
<option selected="0" value="">select your Background</option>
<option value="Science">Science</option>
<option value="Humanities">Humanities</option>
<option value="Commerce">Commerce</option>
</select></span><span>Enter your HSC Background</span>
</li>
<li id="foli0" class="notranslate">
<label class="desc" id="title0" for="Field0">Date of Birth</label>
<span><input id="Field0" type="date" name="birth" class="field text1 fn" size="50"/></span><span>Enter your date of Birth</span>
</li>
<li id="foli0" class="notranslate">
<label class="desc" id="title0" for="Field0">Password</label>
<span><input id="Field0" type="password" name="password" class="field text1 fn" size="50" /></span><span>Enter your password</span>
</li>
<li id="foli0" class="notranslate">
<label class="desc" id="title0" for="Field0">Password</label>
<span><input id="Field0" type="password" name="conpassword" class="field text1 fn" size="50" /></span><span>Enter your password again</span>
</li>
<li id="foli0" class="notranslate">
<label class="desc" id="title0" for="Field0">Email</label>
<span><input id="Field0" type="text" name="email" class="field text1 fn" size="50" /></span><span>Enter a valid email address</span>
</li>
<li class="buttons ">
<div>
<input id="submit" name="submit" class="btn" type="submit" value="Complete Registration"/></div>
</li>
</ul>
</form>
</div>
<?php
include("includes/footer.php");
?>
and the validation javascript code is
function valide()
{
var fname=document.forms["regForm"]["fname"].value;
var username=document.forms["regForm"]["username"].value;
var subject = document.forms["regForm"]["background"].value;
var password=document.forms["regForm"]["password"].value;
var conpassword=document.forms["regForm"]["conpassword"].value;
var email=document.forms["regForm"]["email"].value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
if (fname==null || fname=="" || fname.length<7)
{
alert("Please provide Your full name");
return false;
}
else if (username==null || username=="")
{
if(username.length<6)
{
alert("Username must contains atleast 6 charecters");
}
else
alert("Please provide a username");
return false;
}
else if(subject==null || subject == "")
{
alert("Enter Background");
return false;
}
else if (password==null || password=="")
{
if(password.length<8)
{
alert("Password must contain atleast 8 charecters");
}
else
alert("Please insert your password");
return false;
}
else if (conpassword != password)
{
alert("Confirm password doesn't match");
return false;
}
else if (email==null || email=="")
{
alert("Email must be filled out.");
return false;
}
else if (atpos <1 || dotpos <atpos+2 || dotpos + 2 >= email.length)
{
alert("Not a valid e-mail address");
return false;
}
}
Please help me.
Lets have a look at your function valide()
It has some mistakes and it does not return true when everything is ok...
Since it does not return true, form is not submitted...
Here is a corrected version:
function valide(){
var fname=document.forms["regForm"]["fname"].value;
var username=document.forms["regForm"]["username"].value;
var subject = document.forms["regForm"]["background"].value;
var password=document.forms["regForm"]["password"].value;
var conpassword=document.forms["regForm"]["conpassword"].value;
var email=document.forms["regForm"]["email"].value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
// Let me warn you:
// There are many many people with names less than 7 characters
if (fname==null || fname=="" || fname.length<7) {
alert("Please provide Your full name");
return false;
} // if returned so else is not required
if (username==null || username==""){
if(username.length<6){
alert("Username must contains atleast 6 charecters");
} else
alert("Please provide a username");
return false;
} // if returned so else is not required
if(subject==null || subject == ""){
alert("Enter Background");
return false;
} // if returned so else is not required
if (password == null || password==""){
// length = 0 or password is null here so:
// if(password.length<8) is unnecessary
if(password == ""){
alert("Password must contain at least 8 charecters");
} else
alert("Please insert your password");
return false;
} // if returned so else is not required
if (conpassword != password){
alert("Confirm password doesn't match");
return false;
} // if returned so else is not required
if (email==null || email==""){
alert("Email must be filled out.");
return false;
} // if returned so else is not required
if (atpos <1 || (dotpos <atpos+2) || (dotpos + 2 >= email.length)){
alert("Not a valid e-mail address");
return false;
} // if returned no else needed.
// and now this function should return:
return(true);
}