Displaying an error in certain way - javascript

<!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.

Related

user login simulator,js,validating the username&password,failed

used for validating the strings inputted.
no if conditions works in the js code but the else if one,asking for help.
html code:
<div>
<h2 class="title">login</h2>
<p>usernamehere:</p>
<input type="text" name="username" id="username" placeholder="login">
<p>passwordhere:</p>
<input type="password" name="userpassword" id="userpswd" placeholder="password">
<button id="login">login</button>
</div>
<script src="jquery-3.6.0.min.js" type="text/javascript"></script>
<script src="main.js" type="text/javascript"></script>
js code:
var userenter = $("#username").val()
var pswdenter = $("#userpswd").val()
$("#login").click(function(){
if(userenter == "letsstart" && pswdenter == "start"){
alert("pass");
}
else if(userenter == "" || pswdenter == ""){
alert("enter please")
}
else{
alert("invalid")
}
});
You should read the .val of username and password inside the click handler instead of global . Otherwise it will have the document initial load value of the input . That's why each time you got empty input
$("#login").click(function() {
var userenter = $("#username").val() //
var pswdenter = $("#userpswd").val() //
console.log(userenter,pswdenter)
if (userenter == "letsstart" && pswdenter == "start") {
alert("pass");
} else if (userenter == "" || pswdenter == "") {
alert("enter please")
} else {
alert("invalid")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<h2 class="title">login</h2>
<p>usernamehere:</p>
<input type="text" name="username" id="username" placeholder="login">
<p>passwordhere:</p>
<input type="password" name="userpassword" id="userpswd" placeholder="password">
<button id="login">login</button>
</div>
You are retrieving the values of username and userpswd once and then using it in the click handler. So your if statement is always looking at the values from the first time they were set (probably on page load).
You should move the value retrieval code inside you click handler.
$("#login").click(function(){
var userenter = $("#username").val()
var pswdenter = $("#userpswd").val()
...
});
You have to get the values of #username and #userpswd everytime you click on the "login" button. Otherwise, userenter and pswdenter will be empty when you will check if credentials are valid or not, because when you define them #username and #userpswd inputs are empty. I don't know if it's well explained, but here is the code :
$("#login").click(function(){
var userenter = $("#username").val()
var pswdenter = $("#userpswd").val()
if(userenter == "letsstart" && pswdenter == "start"){
alert("pass");
}
else if(userenter == "" || pswdenter == ""){
alert("enter please")
}
else{
alert("invalid")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<h2 class="title">login</h2>
<p>usernamehere:</p>
<input type="text" name="username" id="username" placeholder="login">
<p>passwordhere:</p>
<input type="password" name="userpassword" id="userpswd" placeholder="password">
<button id="login">login</button>
</div>
<script src="jquery-3.6.0.min.js" type="text/javascript"></script>
<script src="main.js" type="text/javascript"></script>

validation messages are appearing on multiple time on button click in

I have made landing page and using jquery after() method for showing validation messages. When User click multiple times validation messages getting appended and input boxes getting out of form clicks after clicks. When I use append() over after() it does not shows validation error messages at all. What can I use methods for showing validation messages? or Do I need to do with fixed height width of form or is there is huge mistake I have done? Thanks. Validation error messages
Form
<div class="col-lg-4 col-md-3 col-sm-3 col-xs-12 " id="e_form">
<h2>Enquiry Form</h2>
<form name="enquiry-form" method="post" action="#" id="enquiry-form" novalidate="">
<div class="form-group">
<input type="text" class="form-control input-height" name="name" id="name" placeholder="Enter your name here" required="required">
</div>
<div class="form-group">
<input type="email" class="form-control input-height" name="email" id="email" placeholder="Enter your Email-ID" required="required">
</div>
<div class="form-group">
<input type="text" class="form-control input-height" name="number" id="phone" placeholder=" Enter your Mobile Number" required="required" maxlength="10">
</div>
<div class="form-group">
<input type="text" class="form-control input-height" name="city" id="city" placeholder="Enter your city" required="required">
</div>
<div class="form-group">
<textarea class="form-control" rows="4" name="details" id="details" placeholder="Enter message here" required="required"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default btn-lg" name="Submit" id="submit" onclick="CheckBlank(event)">Get Started</button>
</div>
</form>
</div>
Jquery Validation
<script>
function CheckBlank(e) {
e.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var city = $('#city').val();
var details = $('#details').val();
if (name === "" && email === "" && phone === "" && city === "" && details === "") {
// $('input,textarea').css("border", "1px solid red");
$("#name").after("<div class='validation' style='color:red;'>Please Enter Your Name</div>");
$("#email").after("<div class='validation' style='color:red;'>Please Enter Your Email ID</div>");
$("#phone").after("<div class='validation' style='color:red;'>Please Enter Your Phone Number</div>");
$("#city").after("<div class='validation' style='color:red;'>Please Enter Your City</div>");
$("#details").after("<div class='validation' style='color:red;'>Please Enter Your Message</div>");
// $("#submit").prop("disabled",true);
}
else if (name === "" || email === "" || phone === "" || city === "" || details === "") {
$("#submit").prop('disabled',false);
$('#name').val() !== '' ? $('#name').css("border", "none") && $('.validation').remove() :
$("#name").after("<div class='validation' style='color:red;'>Please Enter Your Name</div>");
$('#email').val() !== '' && !ValidateEmail($("#email").val()) ? $('#email').css("border", "none") && $('.validation').remove() :
$("#email").after("<div class='validation' style='color:red;'>Please Enter Your Email ID</div>");
$('#phone').val() !== '' ? $('#phone').css("border", "none") && $('.validation').remove() && $('.valid-email').remove():
$("#phone").after("<div class='validation' style='color:red;'>Please Enter Your Phone Number</div>");
$('#city').val() !== '' ? $('#city').css("border", "none") && $('.validation').remove() :
$("#city").after("<div class='validation' style='color:red;'>Please Enter Your city</div>");
$('#details').val() !== '' ? $('#details').css("border", "none") && $('.validation').remove() :
$("#details").after("<div class='validation' style='color:red;'>Please Enter Your Message</div>");
}
else {
$("#submit").after("<div class='greeting' style='color:#3b9a80;'>Thank You !! We Will Contact You Within 24 Hours !!</div>");
$('input,textarea').val("");
$("#submit").prop('disabled',false);
$('.validation').remove();
$(".greeting").fadeOut(5000);
}
}
$("#name,#email,#phone,#city,#details").on("keydown", function(e) {
if (e.which == 9) { // tab key press
$('#name').val() !== '' ? $('#name').css("border", "none") && $('.validation').remove() :
$("#name").after("<div class='validation' style='color:red;'>Please Enter Your Name</div>");
$('#email').val() !== '' && !ValidateEmail($("#email").val()) ? $('#email').css("border", "none") && $('.validation').remove() && $('.valid-email').remove():
$("#email").after("<div class='validation' style='color:red;'>Please Enter Your Email ID</div>");
$('#phone').val() !== '' ? $('#phone').css("border", "none") && $('.validation').remove() && $('.valid-phone').remove():
$("#phone").after("<div class='validation' style='color:red;'>Please Enter Your Phone Number</div>");
$('#city').val() !== '' ? $('#city').css("border", "none") && $('.validation').remove() :
$("#city").after("<div class='validation' style='color:red;'>Please Enter Your city</div>");
$('#details').val() !== '' ? $('#details').css("border", "none") && $('.validation').remove() :
$("#details").after("<div class='validation' style='color:red;'>Please Enter Your Message</div>");
}
});
$("#name,#city").on("keypress", function(e) {
var regex = /^[a-zA-Z ]*$/; // prevent pressing numbers and other symbols
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
} else {
e.preventDefault();
return false;
}
});
$("#phone").on("change", function(e) {
if ($("#phone").val().length != 10) {
$("#phone").append("<div class='valid-phone' style='color:red;'>Please Enter Valid Phone Number</div>");
}
else{
$('.valid-phone').remove();
}
});
$('#phone').keypress(function(key) {
if (key.charCode < 48 || key.charCode > 57) return false; // prevent pressing other than numbers
});
function ValidateEmail(email) {
var expr = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return expr.test(email);
}
$("#email").on("change", function() {
if (!ValidateEmail($("#email").val())) {
$('.validation').remove();
$("#email").append("<div class='valid-email' style='color:red;'>Please Enter Valid Email ID</div>");
} else {
$('.valid-email').remove();
return;
}
});
$("#phone,#email,#phone,#city").on({
keydown: function(e) {
if (e.which === 32) // prevent pressing space bar
return false;
},
change: function() {
this.value = this.value.replace(/\s/g, "");
}
});
</script>
If you want to continue with this procedure, it is pretty hard to handle, when you go with increasing form size. I would suggest you to add span elements of error message container with form input and handle the content alone with validation.
<form id="loginform" name="loginform" action="myurl.com" method="post">
<input type="text" name="username" /><span id="usernameError"></span>
<input type="password" name="password" /><span id="passwordError"></span>
<input type="submit" value="Submit" /></form>
And js code will be like
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;}}
This span will act as a container of error messages and we can have better control over error messages with the help of JavaScript
Just add $('div.validation').remove(); in the CheckBlank(e) method
JSFiddle : https://jsfiddle.net/44Luvysr/11/

How to print error message under respective input field using javascript validation in php [closed]

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>

JS Form validation (Regex, or anything)

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>

Javascript Validation doesn't work

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">&nbspName</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">&nbspGender</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">&nbspAge</label>
<span>
<tr>
<select name="Age">
</tr>
</span>
<script type="text/javascript">
listAge()
</script>
</select>
<li class="buttons">
<label class="description" for="element_3">&nbspPhone 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">&nbspEmail 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">&nbspAddress</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">&nbspReason 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">&nbspAttending 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!

Categories

Resources