Okay, I'm trying to get a contact form to work and it is, sort of. The data is passing through, but I can't get the jQuery to work. If I type in two different email addresses it doesn't catch it. Here is the relevant code I used:
HTML
<aside>
<form action="sendmail.php" method="post" name="contact_form" id="contact_form">
<fieldset>
<legend>sign up now!</legend><br>
<p>Sign up for my email list and get a free mini coloring book!</p><br>
<img src="Images/minicoloirngbook.jpg" alt="mini coloring book"><br>
<label for="name"> Name:</label>
<input type="text"name="name" id="name" required><span>*</span><br>
<label for="email">Email Address:</label>
<input type="email" name="email" id="email" required><span>*</span><br>
<label for="verify">Verify Email:</label>
<input type="email" name="verify" id="verify" required> <span>*</span><br>
<div id="buttons">
<input type="submit" id="submit" value="Sign Up">
</div>
</fieldset>
</form>
</aside>
and here is the Javascript:
$("#contact_form").submit(event => {
let isValid = true;
// validate the first name entry
const name = $("#name").val().trim();
if (name == "") {
$("#name").next().text("This field is required.");
isValid = false;
} else {
$("#name").next().text("");
}
$("#name").val(name);
// validate the email entry with a regular expression
const emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
const email = $("#email").val().trim();
if (email == "") {
$("#email").next().text("This field is required.");
isValid = false;
} else if ( !emailPattern.test(email) ) {
$("#email").next().text("Must be a valid email address.");
isValid = false;
} else {
$("#email").next().text("");
}
$("#email").val(email);
// validate the verify entry
const verify = $("#verify").val().trim();
if (verify == "") {
$("#verify").next().text("This field is required.");
isValid = false;
} else if (verify !== email) {
$("#verify").next().text("Must match first email entry.");
isValid = false;
} else {
$("#verify").next().text("");
}
$("#verify").val(verify);
// prevent the submission of the form if any entries are invalid
if (isValid == false) {
event.preventDefault();
}
}),
I think that the answer is probably something really simple that I can't see and would appreciate your help in figuring it out.
This should do it. Here is the jsfiddle if you like to play with the code: https://jsfiddle.net/bogatyr77/xk6ez3aq/7/
$("form").submit(function(e) {
var name = $("#a").val();
if (name == "") {
$("#nameerror").text("This field is required.");
alert('false');
} else {
alert('true');
$("#nameerror").remove();
}
//email1
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
const email = $("#b").val();
if (email == "") {
$("#email1error").text("This field is required.");
isValid = false;
} else if (!emailPattern.test(email)) {
$("#email1error").text("Must be a valid email address.");
isValid = false;
} else {
$("#email1error").remove();
}
//eamil 2
var verify = $("#c").val();
if (verify == "") {
$("#email2error").text("This field is required.");
isValid = false;
} else if (verify !== email) {
$("#email2error").text("Must match first email entry.");
isValid = false;
} else {
$("#email2error").remove();
}
if (isValid == false) {
event.preventDefault();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="javascript:alert('ok')">
<label for="name"> Name:</label>
<input type="text" name="name" id="a"><span>*</span>
<div id="nameerror"></div><br>
<label for="email">Email Address:</label>
<input type="text" name="email" id="b"><span>*</span>
<div id="email1error"></div><br>
<label for="verify">Verify Email:</label>
<input type="text" name="verify" id="c"> <span>*</span>
<div id="email2error"></div><br>
<input type="submit" value="submit" />
</form>
<div></div>
So the two Functions (chForumular() and validate_user_text()) have both to be true to submit the form. Right now you cant send the form without fil in the username, age(in the code Alter) and your E-Mail. but the second function (validate_user_text) should check if there is any swear word in the message (=Nachricht) right know it submits the form after you fil in the three fields (e-mail, name and age). iven if you type in an swearword in the textarea. (something like: sorry ((asshole)))
If you dont understand a Word you think could be important just write the word to me so I can translate...(German and Swissgerman Words in the Code)
Here is my code so far:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/kontakt.css" media="screen">
<title>Kontaktseite</title>
<meta charset="utf-8">
<script type="text/javascript">
function chkFormular () {
if (document.Formular.User.value == "") {
alert("Enter your Name, Please!");
document.Formular.User.focus();
return false;
}
// if (document.Formular.Ort.value == "") {
// alert("Bitte Ihren Wohnort eingeben!");
// document.Formular.Ort.focus();
// return false;
// }
if (document.Formular.Mail.value == "") {
alert("Enter your E-Mail, please!");
document.Formular.Mail.focus();
return false;
}
if (document.Formular.Mail.value.indexOf("#") == -1) {
alert("No valid E-Mail, address!");
document.Formular.Mail.focus();
return false;
}
if (document.Formular.Alter.value == "") {
alert("Enter your Age, please!");
document.Formular.Alter.focus();
return false;
}
var chkZ = 1;
for (i = 0; i < document.Formular.Alter.value.length; ++i)
if (document.Formular.Alter.value.charAt(i) < "0" ||
document.Formular.Alter.value.charAt(i) > "9")
chkZ = -1;
if (chkZ == -1) {
alert("Your Age is not a Number!");
document.Formular.Alter.focus();
return false;
}
}
</script>
<script language="JavaScript1.2">
// Word Filter
// (c) 2002 Premshree Pillai
// http://www.qiksearch.com
// http://javascript.qik.cjb.net
var swear_words_arr=new Array("arschloch","idiot","terror", "wixer", "wixxer", "hure", "hurensohn", "hurenson", "motherfucker", "neger", "sauhund", "arsch", "fuck", "fucking", "shit", "satan",
"satanus", "figge", "ficken", "scheiss", "drecksjude", "drecksjud", "i hoff du stirbsch", "geh sterben", "verrecken", "verreck doch", "chrüppel", "krüppel", "chrüpel", "krüpel", "saftsack",
"sackratte", "god damit", "goddamit", "godvertammi", "gopfetammi", "chrüzsatan", "gottvertammi", "gottpfertami", "gopfeteckel", "verflucht", "verfluecht", "damisiech", "ich hoffe du stirbst",
"stirb", "geh sterben", "ass", "asshole", "cunt"); //corrected commas
var swear_alert_arr=new Array;
var swear_alert_count=0;
function reset_alert_count()
{
swear_alert_count=0;
}
function validate_user_text()
{
reset_alert_count();
var compare_text=document.Formular.user_text.value;
for(var i=0; i<swear_words_arr.length; i++)
{
for(var j=0; j<(compare_text.length); j++)
{
if(swear_words_arr[i]==compare_text.substring(j,(j+swear_words_arr[i].length)).toLowerCase())
{
swear_alert_arr[swear_alert_count]=compare_text.substring(j,(j+swear_words_arr[i].length));
swear_alert_count++;
}
}
}
var alert_text="";
for(var k=1; k<=swear_alert_count; k++)
{
alert_text+="\n" + "(" + k + ") " + swear_alert_arr[k-1];
}
if(swear_alert_count>0)
{
alert("The following Words are not allwoed:\n_______________________________\n" + alert_text + "\n_______________________________");
document.Formular.user_text.select();
}
else
{
document.Formular.submit();
}
}
function select_area()
{
document.Formular.user_text.select();
}
window.onload=reset_alert_count;
</script>
</head>
<body>
<h1>Kontaktformular</h1>
<nav>
<ul class="nav">
<li>Zurück</li>
</ul>
</nav>
<div id="part1">
<form name="Formular" action="http://www.formular-chef.de/fc.cgi" enctype="multipart/form-data" method="post" onSubmit="return chkFormular()">
<input type="hidden" name="empfaenger" value="benjamin.laubeX§Xbrueggli.ch">
<!--<input type="hidden" name="empfaenger" value="dominik.widmerX§Xbrueggli.ch">-->
</div>
<div id="part2">
<pre>
Name: <input type="text" size="40" name="User"><br>
E-Mail: <input type="text" size="40" name="Mail"><br>
Alter: <input type="text" size="40" name="Alter"><br>
Geschlecht: <select name="geschlecht">
<option selected>-</option>
<option>männlich</option>
<option>weiblich</option>
</select>
</div>
<p id="nachricht">Deine Nachricht:</p>
<div id="part3">
<textarea rows="10" cols="40" name="user_text" onclick="select_area()" placeholder="Ihre Nachricht..."></textarea>
</div>
<div id="part4">
Zum Absenden muss eine Internet-Verbindung bestehen!
<br><br>
<input type="submit" value="Absenden" onclick="validate_user_text();"><input type="reset" value="Abbrechen">
</div>
</pre>
</form>
</body>
</html>
This should do the trick:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/kontakt.css" media="screen">
<title>Kontaktseite</title>
<meta charset="utf-8">
<script type="text/javascript">
function chkFormular () {
if (document.Formular.User.value == "") {
alert("Enter your Name, Please!");
document.Formular.User.focus();
return false;
}
// if (document.Formular.Ort.value == "") {
// alert("Bitte Ihren Wohnort eingeben!");
// document.Formular.Ort.focus();
// return false;
// }
if (document.Formular.Mail.value == "") {
alert("Enter your E-Mail, please!");
document.Formular.Mail.focus();
return false;
}
if (document.Formular.Mail.value.indexOf("#") == -1) {
alert("No valid E-Mail, address!");
document.Formular.Mail.focus();
return false;
}
if (document.Formular.Alter.value == "") {
alert("Enter your Age, please!");
document.Formular.Alter.focus();
return false;
}
var chkZ = 1;
for (i = 0; i < document.Formular.Alter.value.length; ++i)
if (document.Formular.Alter.value.charAt(i) < "0" ||
document.Formular.Alter.value.charAt(i) > "9")
chkZ = -1;
if (chkZ == -1) {
alert("Your Age is not a Number!");
document.Formular.Alter.focus();
return false;
}
return true;
}
</script>
<script language="JavaScript1.2">
// Word Filter
// (c) 2002 Premshree Pillai
// http://www.qiksearch.com
// http://javascript.qik.cjb.net
var swear_words_arr=new Array("arschloch","idiot","terror", "wixer", "wixxer", "hure", "hurensohn", "hurenson", "motherfucker", "neger", "sauhund", "arsch", "fuck", "fucking", "shit", "satan",
"satanus", "figge", "ficken", "scheiss", "drecksjude", "drecksjud", "i hoff du stirbsch", "geh sterben", "verrecken", "verreck doch", "chrüppel", "krüppel", "chrüpel", "krüpel", "saftsack",
"sackratte", "god damit", "goddamit", "godvertammi", "gopfetammi", "chrüzsatan", "gottvertammi", "gottpfertami", "gopfeteckel", "verflucht", "verfluecht", "damisiech", "ich hoffe du stirbst",
"stirb", "geh sterben", "ass", "asshole", "cunt");
var swear_alert_arr=new Array;
var swear_alert_count=0;
function reset_alert_count()
{
swear_alert_count=0;
}
function validate_user_text()
{
reset_alert_count();
var compare_text=document.Formular.user_text.value;
for(var i=0; i<swear_words_arr.length; i++)
{
for(var j=0; j<(compare_text.length); j++)
{
if(swear_words_arr[i]==compare_text.substring(j,(j+swear_words_arr[i].length)).toLowerCase())
{
swear_alert_arr[swear_alert_count]=compare_text.substring(j,(j+swear_words_arr[i].length));
swear_alert_count++;
}
}
}
var alert_text="";
for(var k=1; k<=swear_alert_count; k++)
{
alert_text+="\n" + "(" + k + ") " + swear_alert_arr[k-1];
}
if(swear_alert_count>0)
{
alert("The following Words are not allwoed:\n_______________________________\n" + alert_text + "\n_______________________________");
document.Formular.user_text.select();
}
else
{
return true;
}
}
function select_area()
{
document.Formular.user_text.select();
}
window.onload=reset_alert_count;
</script>
</head>
<body>
<h1>Kontaktformular</h1>
<nav>
<ul class="nav">
<li>Zurück</li>
</ul>
</nav>
<div id="part1">
<form id="frmFormular" name="Formular" action="http://www.formular-chef.de/fc.cgi" enctype="multipart/form-data" method="post">
<input type="hidden" name="empfaenger" value="benjamin.laubeX§Xbrueggli.ch">
<!--<input type="hidden" name="empfaenger" value="dominik.widmerX§Xbrueggli.ch">-->
</div>
<div id="part2">
<pre>
Name: <input type="text" size="40" name="User"><br>
E-Mail: <input type="text" size="40" name="Mail"><br>
Alter: <input type="text" size="40" name="Alter"><br>
Geschlecht: <select name="geschlecht">
<option selected>-</option>
<option>männlich</option>
<option>weiblich</option>
</select>
</div>
<p id="nachricht">Deine Nachricht:</p>
<div id="part3">
<textarea rows="10" cols="40" name="user_text" onclick="select_area()" placeholder="Ihre Nachricht..."></textarea>
</div>
<div id="part4">
Zum Absenden muss eine Internet-Verbindung bestehen!
<br><br>
<input type="submit" id="sendButton" value="Absenden">
<input type="reset" value="Abbrechen">
<script>
document.getElementById('sendButton').onclick = function() {
if (chkFormular() && validate_user_text()) {
document.formular.submit();
return true;
} else {
return false;
}
}
</script>
</div>
</pre>
</form>
</body>
</html>
Just change the submit part.
onSubmit="return chkFormular() && validate_user_text()"
this program runs correctly.. my task is, when name field left empty then (please enter your name )this error will be generated and when i type wrong input(like numbers)then (only alphabets and white space are allowed)this error message has to be generate. how can i do this.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Validation tutorial</title>
<script>
function validateName(x){
// Validation rule
var re = /[A-Za-z -']$/;
// Check input
if(re.test(document.getElementById(x).value)){
// Style green
document.getElementById(x).style.borderColor ='#3BFF3B';
// Hide error prompt
document.getElementById(x + 'Error').style.display = "none";
return true;
}else{
// Style red
document.getElementById(x).style.borderColor ='#FF0000';
// Show error prompt
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
// Validate email
function validateEmail(email){
var re = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(re.test(email)){
document.getElementById('email').style.borderColor ='#3BFF3B';
document.getElementById('emailError').style.display = "none";
return true;
}else{
document.getElementById('email').style.borderColor ='#FF0000';
return false;
}
}
// Validate Select boxes
function validateSelect(x){
if(document.getElementById(x).selectedIndex !== 0){
document.getElementById(x).style.borderColor ='#3BFF3B';
document.getElementById(x + 'Error').style.display = "none";
return true;
}else{
document.getElementById(x).style.borderColor ='#FF0000';
return false;
}
}
function validateRadio(x){
if(document.getElementById(x).checked){
return true;
}else{
return false;
}
}
function validateCheckbox(x){
if(document.getElementById(x).checked){
return true;
}
return false;
}
function validateForm(){
// Set error catcher
var error = 0;
// Check name
if(!validateName('name')){
document.getElementById('nameError').style.display = "block";
error++;
}
// Validate email
if(!validateEmail(document.getElementById('email').value)){
document.getElementById('emailError').style.display = "block";
error++;
}
// Validate animal dropdown box
if(!validateSelect('subject')){
document.getElementById('subjectError').style.display = "block";
error++;
}
// Validate Radio
if(validateRadio('male')){
}else if(validateRadio('female')){
}else{
document.getElementById('genderError').style.display = "block";
error++;
}
// Don't submit form if there are errors
if(error > 0){
return false;
}
}
</script>
</head>
<body>
<form action="" onsubmit="return validateForm()">
<label for="name">Name</label>
<input type="text" name="name" id="name" onblur="validateName(name)" />
<span id="nameError" style="display: none;">only alphabates and white space are allowed</span>
<br><br>
<label for="email">Email</label>
<input type="text" name="email" id="email" onblur="validateEmail(value)" />
<span id="emailError" style="display: none;">You must enter a valid email address</span>
<br><br>
<label for="hand">Gender</label>
<ul>
<li>
<input type="radio" name="gender" id="male" value="male" onblur="validateRadio(id)" />
<label for="left">male</label>
</li>
<li>
<input type="radio" name="gender" id="female" value="female" onblur="validateRadio(id)" />
<label for="right">female</label>
</li>
</ul>
<span class="validateError" id="genderError" style="display: none;">Please select gender</span>
<br><br>
<label for="subject">Favourite Subject</label>
<select name="subject" id="subject" onblur="validateSelect(name)">
<option value="">SUBJECTS</option>
<option value="php">PHP</option>
<option value="java">JAVA</option>
<option value="sql">SQL</option>
</select>
<span class="validateError" id="subjectError" style="display: none;">You must select your favourite subject</span>
<br><br>
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Validation tutorial</title>
<script>
function validateName(x){
// Validation rule
var re = /[A-Za-z -']$/;
// Check input
if(re.test(document.getElementById(x).value)){
// Style green
document.getElementById(x).style.borderColor ='#3BFF3B';
// Hide error prompt
document.getElementById(x + 'Error').style.display = "none";
return true;
}else if(document.getElementById(x).value === ''){
//This is for an empty string or if name was not entered.
// Style red
document.getElementById(x).style.borderColor ='#FF0000';
// Show error prompt
document.getElementById(x + 'Error2').style.display = "block";
return false;
}else{
// Style red
document.getElementById(x).style.borderColor ='#FF0000';
// Show error prompt
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
// Validate email
function validateEmail(email){
var re = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(re.test(email)){
document.getElementById('email').style.borderColor ='#3BFF3B';
document.getElementById('emailError').style.display = "none";
return true;
}else{
document.getElementById('email').style.borderColor ='#FF0000';
return false;
}
}
// Validate Select boxes
function validateSelect(x){
if(document.getElementById(x).selectedIndex !== 0){
document.getElementById(x).style.borderColor ='#3BFF3B';
document.getElementById(x + 'Error').style.display = "none";
return true;
}else{
document.getElementById(x).style.borderColor ='#FF0000';
return false;
}
}
function validateRadio(x){
if(document.getElementById(x).checked){
return true;
}else{
return false;
}
}
function validateCheckbox(x){
if(document.getElementById(x).checked){
return true;
}
return false;
}
function validateForm(){
// Set error catcher
var error = 0;
// Check name
if(!validateName('name')){
document.getElementById('nameError').style.display = "block";
error++;
}
// Validate email
if(!validateEmail(document.getElementById('email').value)){
document.getElementById('emailError').style.display = "block";
error++;
}
// Validate animal dropdown box
if(!validateSelect('subject')){
document.getElementById('subjectError').style.display = "block";
error++;
}
// Validate Radio
if(validateRadio('male')){
}else if(validateRadio('female')){
}else{
document.getElementById('genderError').style.display = "block";
error++;
}
// Don't submit form if there are errors
if(error > 0){
return false;
}
}
</script>
</head>
<body>
<form action="" onsubmit="return validateForm()">
<label for="name">Name</label>
<input type="text" name="name" id="name" onblur="validateName(name)" />
<span id="nameError" style="display: none;">only alphabates and white space are allowed</span>
<span id="nameError2" style="display: none;">please enter a name</span>
<br><br>
<label for="email">Email</label>
<input type="text" name="email" id="email" onblur="validateEmail(value)" />
<span id="emailError" style="display: none;">You must enter a valid email address</span>
<br><br>
<label for="hand">Gender</label>
<ul>
<li>
<input type="radio" name="gender" id="male" value="male" onblur="validateRadio(id)" />
<label for="left">male</label>
</li>
<li>
<input type="radio" name="gender" id="female" value="female" onblur="validateRadio(id)" />
<label for="right">female</label>
</li>
</ul>
<span class="validateError" id="genderError" style="display: none;">Please select gender</span>
<br><br>
<label for="subject">Favourite Subject</label>
<select name="subject" id="subject" onblur="validateSelect(name)">
<option value="">SUBJECTS</option>
<option value="php">PHP</option>
<option value="java">JAVA</option>
<option value="sql">SQL</option>
</select>
<span class="validateError" id="subjectError" style="display: none;">You must select your favourite subject</span>
<br><br>
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
</body>
</html>
There are much better ways to do this. This is not an elegant way. I see this code is from an example or tutorial. Please check other tutorials on this subject, as this is just a quick way of implementing what you want.
I've been working on this assignment for the longest while. My form validations weren't working previously but then I found out what the error was & everything was working perfectly.
Later on, I had made some changes to the code then deleted those changes and now the validations aren't working again & I can't seem to find what the problem is this time.
Below is my unfinished code:
function validateEmail() {
var email = document.getElementById('email').value;
if( email==null || email=="")
{
alert("Please input an email address");
}
}
function validateFName() {
var firstname = document.getElementById('firstname').value;
if( firstname==null || firstname=="")
{
alert("Please input a last name");
return false;
}
}
function validateLName() {
var lastname = document.getElementById('lastname').value;
if( lastname==null || lastname=="")
{
alert("Please input a last name");
}
}
function validateGender() {
var gender = document.getElementById('gender').value;
if( gender==null || gender=="")
{
alert("Please select a gender");
}
}
function validateDate() {
var date = document.getElementById('date').value;
if( date==null || date=="")
{
alert("Please select a date");
}
}
function validateVName() {
var vname = document.getElementById('vname').value;
if( vname==null || vname=="")
{
alert("Please input a victim's name");
}
}
function validateVEmail() {
var vemail = document.getElementById('vemail').value;
if( vemail==null || vemail=="")
{
alert("Please input a victim's email");
}
}
<div id="navi">
<nav>
<ul class="fancyNav">
<li id="home">Home</li>
<li id="news">TRUTH</li>
<li id="about">DARE</li>
</ul>
</nav>
</div>
<div id="box">
<form id="truth">
<h1> Truth </h1>
<label> First Name: </label> <input type="text" name="firstname" id="firstname" maxlength="30" placeholder="John" /> <br><br>
<label> Last Name: </label> <input type="text" name="lastname" id="lastname" maxlength="30" placeholder="Doe" /> <br><br>
<label> Email:</label> <input type="text" name="email" id="email" /> <br><br>
<label> Male </label><input type="radio" name="gender" id="gender" value="male"/>
<label> Female </label><input type="radio" name="gender" id="gender" value="female"/> <br><br>
<label> Date to be performed: </label><input type="date" name="date" id="date" /><br><br>
<h2> Victim </h2>
<label> Name: </label> <input type="text" name="vname" id="vname" maxlength="30" /><br><br>
<label> Email:</label> <input type="text" name="vemail" id="vemail" /> <br><br>
<h2> Please select a truth questions below </h2> <br>
<input type="radio" name="truth" value="q1"> Have you ever fallen and landed on your head? <br>
<input type="radio" name="truth" value="q2"> Have you ever return too much change? <br>
<input type="radio" name="truth" value="q3"> Have you ever been admitted into the hospital? <br>
<input type="radio" name="truth" value="q4"> Have you ever baked a cake? <br>
<input type="radio" name="truth" value="q5"> Have you ever cheated on test? <br>
<input type="radio" name="truth" value="q6"> Did you ever wish you were never born? <br>
<input type="radio" name="truth" value="q7"> Did you ever hide from Sunday School? <br><br>
<input type="submit" onclick="validateFName(); validateLName(); validateGender(); validateDate(); validateVName(); validateVEmail();" /> <br>
</form>
</div>
<input type="submit" onclick="validateFName(); validateLName(); validateGender(); v
typo in function name, onclick="validateFName()...
it should be validateLName()
and you define duplicate
<!DOCTYPE html>
<html> // remove this one
The best possible solution would be to not use any alert boxes at all but instead embed the error message next to the place of the error, but that would be more involved. Instead, to stick with this solution, first add an id to your submit button:
<button type="submit" id="truth-submit">Submit</button>
Then, attach an onclick handler through JavaScript (and rewrite your code to be more re-usable):
// Only run when the window fully loads
window.addEventListener("load", function() {
function validateEmail() {
var email = document.getElementById("email").value;
if (email === null || email === "") {
return "Please input an email address";
}
return "";
}
function validateFName() {
var firstname = document.getElementById("firstname").value;
if (firstname === null || firstname === "") {
return "Please input an first name";
}
return "";
}
function validateLName() {
var lastname = document.getElementById("lastname").value;
if (lastname === null || lastname === "") {
return "Please input an last name";
}
return "";
}
function validateGender() {
var gender = document.getElementById("gender").value;
if (gender === null || gender === "") {
return "Please select a gender";
}
return "";
}
function validateDate() {
var date = document.getElementById("date").value;
if (date === null || date === "") {
return "Please select a date";
}
return "";
}
function validateVName() {
var vname = document.getElementById("vname").value;
if (vname === null || vname === "") {
return "Please input a victim's name";
}
return "";
}
function validateVEmail() {
var vemail = document.getElementById("vemail").value;
if (vemail === null || vemail === "") {
return "Please input a victim's email";
}
return "";
}
document.getElementById("truth-submit").addEventListener("click", function(event) {
// Grab all of the validation messages
var validationMessages = [validateFName(), validateLName(),
validateGender(), validateDate(), validateVName(), validateVEmail()];
var error = false;
// Print out the non-blank ones
validationMessages.forEach(function(message) {
if (message) {
alert(message);
error = true;
}
});
// Stop submission of the form if an error occurred
if (error) {
event.preventDefault();
}
}, false);
}, 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);
}