I feel like I must be missing something so simple as this form field validation method has worded well in the past for me. I believe all file paths are correct, but any time I hit submit it generates an email regardless of the field content.
The test site is PortfolioPrep
<form action="<?php echo base_url()?>" method="POST">
<input type="hidden" name="subject" id="subject" value="Portfolio Prep From Reply">
<div class="dot_spacer_lt_green"></div>
<label>NAME</label><dl class="field row">
<dt class="text"><input name="name" type="text" id="name" placeholder="Contact Name" /></dt>
<dd class="msg"><span class="caret"></span>You filled this out wrong.</dd>
</dl>
<label>EMAIL</label><dl class="field row">
<dt class="text"><input name="from" type="text" id="from" placeholder="Contact Email" /></dt>
<dd class="msg"><span class="caret"></span>You filled this out wrong.</dd>
</dl>
<div class="dot_spacer_lt_green"></div>
<ul class="field row">
<li>
<label class="radio" for="high_school">HIGH SCHOOL</label>
<input name="radio1" type="radio" form="high_school" value="High School">
</li>
<li>
<label class="radio" for="recent_graduate">RECENT GRADUATE</label>
<input name="radio1" type="radio" form="recent_graduate" value="Recent Graduate">
</li>
</ul>
<div class="dot_spacer_lt_green"></div>
<dl class="field row">
<dt class="textarea"><textarea name="message" id="message" placeholder="Text Field"></textarea></dt>
<dd class="error msg"><span class="caret"></span>You filled this out wrong.</dd>
</dl>
<input type="image" src="<?php echo base_url()?>img/submit.png" alt="Submit" onClick="return validateForm()"/>
<div class="dot_spacer_lt_green"></div>
</form>
</div>
<div class="one columns"></div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="<?php echo base_url()?>js/libs/jquery-1.7.2.min.js"><\/script>')</script>
<script src="<?php echo base_url()?>js/libs/gumby.min.js"></script>
<script src="<?php echo base_url()?>js/plugins.js"></script>
<script src="<?php echo base_url()?>js/main.js"></script>
<script src="<?php echo base_url()?>js/libs/modernizr-2.0.6.min.js"></script>
<!-- end scripts-->
<!-- Change UA-XXXXX-X to be your site's ID -->
<script>
$(document).ready(function(e) {
$("#from").blur(function(){
if($(this).val()=='' )
{
$(this).css('color','#000');
$(this).val('Email')
}
});
$("#fron").click(function(){
if($(this).val()=='Email' || $("#fron").val()=='Please enter a valid email.' || $("#from").val()=='Please enter your email.')
{$(this).val('')}
});
$("#name").blur(function(){
if($(this).val()=='')
{$(this).css('color','#000');
$(this).val('Contact Name')}
});
$("#name").click(function(){
if($(this).val()=='Please enter your name.' || $(this).val()=='Contact Name')
{$(this).val('')}
});
function validateForm()
{
var i=0;
if($("#name").val()=='Contact Name' || $("#name").val()=='Please enter your name.')
{ $("#name").css('color','red');
$("#name").val('Please enter your name.');
i++;
}
if($("#from").val()=='Email' || $("#from").val()=='Please enter your email.' || $("#from").val()=='Please enter a valid email.')
{
$("#from").css('color','red');
$("#from").val('Please enter your email.');
i++;
}
else
{
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
if(!filter.test($("#from").val()))
{
$("#from").css('color','red');
$("#from").val('Please enter a valid email.');
i++;
}
}
if(i>0)
{
return false;
}
else{
//$("#contactusform").submit();
}
}
window._gaq = [['_setAccount','UAXXXXXXXX1'],['_trackPageview'],['_trackPageLoadTime']];
Modernizr.load({
load: ('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js'
});
</script>
You have some typos in your Javascript:
"#fron" needs to become "#from" in the following section:
$("#fron").click(function(){
if($(this).val()=='Email' || $("#fron").val()=='Please enter a valid email.' || $("#from").val()=='Please enter your email.')
{$(this).val('')}
});
Related
I write this code for a login form in function.php file in Wordpress:
$name = $_POST['dx'];
$pass = $_POST['SX'];
$submitbutton= $_POST['commit'];
if ( isset($submitbutton) ) {
if( isset($name) && empty($name) ){
echo '<script> var errorMsg = document.getElementById("errorMsg");
errorMsg.innerHTML = "username is empty";
errorMsg.style.display = "block"; </script>';
}
else if( isset($pass) && empty($pass) ){
$name = "";
$pass = "";
echo '<script> var errorMsg = document.getElementById("errorMsg");
errorMsg.innerHTML = "password is empty";
errorMsg.style.display = "block"; </script>';
}
}
I got an error Cannot read property 'style' of null
HTML code
<div class="login">
<ul class="errorMessages" id="errorMsg">
<li></li>
</ul>
<form method="post" action="">
<p>
<label for="dx">username</label><br>
<input type="text" name="dx" value="" id="dx" maxlength="20">
</p>
<p>
<label for="SX">password</label><br>
<input id="SX" type="password" name="SX" value="" maxlength="30"
class="keyboardInput" vki_attached="true">
</p>
<div class="separator"></div>
<p class="submit">
<input type="submit" name="commit" value="login">
</p>
</form>
</div>
I want to check the form fields, if fields were empty, show the error messege above the form.
Something like this image:
How can I use script code in right way in PHP? and how can I resolve this error?
<div class="login">
<ul class="errorMessages" id="errorMsg">
</ul>
<form method="post" action="">
<p>
<label for="dx">username</label><br>
<input type="text" name="dx" value="" id="dx" maxlength="20">
</p>
<p>
<label for="SX">password</label><br>
<input id="SX" type="password" name="SX" value="" maxlength="30" class="keyboardInput" vki_attached="true"><img src="http://account.taminm.ir/wp-content/uploads/2020/01/keyboard.png" alt="Display virtual keyboard interface" class="keyboardInputInitiator" title="Display virtual keyboard interface">
</p>
<div class="separator"></div>
<p class="submit">
<input type="submit" name="commit" value="login">
</p>
</form>
</div>
<script type="text/javascript">
const loginWrapper = document.querySelector('.login'),
errorContainer = loginWrapper.querySelector('.errorMessages'),
form = loginWrapper.querySelector('form');
form.addEventListener('submit', function(e) {
e.preventDefault();
const username = form.querySelector('#dx').value.trim(),
password = form.querySelector('#SX').value.trim();
if ( !username ) {
errorContainer.innerHTML = 'username is empty';
} else if (!password) {
errorContainer.innerHTML = 'password is empty';
} else {
form.submit()
}
});
</script>
I have written java script to validate signup information but it is not working when i joined it to action.php file.but it works fine in html file.
it also dosen't work after refreshing of the page.i am not getting what is wrong with it.please do help to solve this problem.
it is signup page.
<?php include 'conn.php'; ?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="signup.css">
</head>
<body onload="form.reset();"">
<div class="container">
<div id="grad">
<ul>
<li style="">Helping Hands...</li>
<li style="float:right"><a class="active" href="#about"> Have an account? Log in</a></li>
</ul>
</div>
<form name=form action="#" onsubmit="return validate()" autocomplete=on method="post">
<div class="outsidebox" >
<div class='login'>
<h2>Register</h2>
<div class="agree1">
<label style="margin-left: 30px;"> <input id="ngo" type="radio" name="option" value="ngo" checked>NGO</label>
<label style="margin-left:30px;"><input id="ind" type="radio" name="option" value="ind">INDIVIDUAL</label>
</div>
<span><input name='uname' placeholder='Username' type='text' value='<?php echo $_SESSION['name']; $_SESSION['name']='';?>'>
<p id="username" style="font-size: 12px;color:red;"></p>
</span>
<span><input name='email' placeholder='E-Mail Address' type='text'>
<p id="email" style="font-size: 12px;color:red;"></p></span>
<span> <input name='password' placeholder='Password' type='password'>
<p id="password" style="font-size: 12px;color:red;"></p></span>
<span><input name='passwordcon' placeholder=' Confirm Password' type='password'>
<p id="passwordcon" style="font-size: 12px;color:red;"></p></span>
<span><input name='fullname' placeholder='Enter Your Full Name ' type='text'>
<p id="fullname" style="font-size: 12px;color:red;"></p></span>
<div id="a1" >
<strong>PLEASE SELECT FIELDS</strong><br>
<div class="fields">
<select name="fields" id="fields">
<option value="child">Child Welfare</option>
<option value="education">Child Education</option>
<option value="relief">Disaster Management and relief</option>
<option value="envir">Environment</option>
<option value="animals">Animals</option>
</select>
</div>
</div>
<div class='agree'>
<input id='agree' name='agree' type='checkbox'>
<label for='agree'></label>Accept rules and conditions
</div>
<input class='animated' type='submit' value='Register'>
<a class='forgot' href='#'>Already have an account?</a>
</div>
</div>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ngo").click(function(){
$("#a1").show();
});
$("#ind").click(function(){
$("#a1").hide();
});
});
</script>
<script language="javascript">
function validate(){
var flag=1;
var form=document.forms.form;
var user=form.username.value;
if(user==null || user==""){
user="please enter username";
document.getElementById("username").innerHTML=user;
flag=0;
}
else{
document.getElementById("username").innerHTML="";
}
var email=form.email.value;
if(email==null ||email==""){
email="please enter email";
document.getElementById("email").innerHTML=email;
flag=0;
}
else{
document.getElementById("email").innerHTML="";
}
var password=form.password.value;
if(password==null || password==""){
password="please enter password";
document.getElementById("password").innerHTML=password;
flag=0;
}
else{
document.getElementById("password").innerHTML="";
}
var passwordcon=form.passwordcon.value;
if(passwordcon==null || passwordcon==""){
passwordcon="please conform password";
document.getElementById("passwordcon").innerHTML=passwordcon;
flag=0;
}
else{
document.getElementById("passwordcon").innerHTML="";
}
if(passwordcon!=password){
passwordcon =" pasword confirmation fail";
document.getElementById("passwordcon").innerHTML=passwordcon;
flag=0;
}
else{
document.getElementById("passwordcon").innerHTML="";
}
var fullname=form.fullname.value;
if (fullname==null || fullname=="") {
fullname="Enter full name";
document.getElementById("fullname").innerHTML=fullname;
flag=0;
}
else{
document.getElementById("fullname").innerHTML="";
}
if(flag==0){
return false;
}
else{
return true;
`enter code here` }
}
</script>
</html>
it is my action.php as inputs.php in which i have written defined session variables.to send error to signup page;and also i am performing
email validation check.Then i check username is used or not to insert this
into the database.
.
<?php include 'conn.php'; ?>
<?php
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$password=$_POST["password"];
$fullname=$_POST["fullname"];
$uname=$_POST["uname"];
$ngo=$_POST["option"];
$field=$_POST["field"];
$email=$_POST["email"];
$_SESSION['uerr']='';
$_SESSION['emailerr']='';
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === true){
$emailerr="Inavalid Email";
$_SESSION['email']=$emailerr;
$sql="SELECT * FROM user WHERE uname='$uname' LIMIT 1";
$result=mysqli_query($conn,$sql);
$countu= mysqli_num_rows($result);
echo "in emailerr".$countu;
if($countu==0)
{
$_SESSION['fullname']=$fullname;
$_SESSION['field']=$field;
$_SESSION['name']=$uname;
$_SESSION['emailerr']=$emailerr;
$_SESSION['email']='';
die(header('Location:signup2.php'));
}
else{
$uerr="USER NAME already taken";
$_SESSION['fullname']=$fullname;
$_SESSION['field']=$field;
$_SESSION['name']='';
$_SESSION['uerr']=$uerr;
$_SESSION['emailerr']=$emailerr;
$_SESSION['email']='';
echo "in esle";
die(header('Location:signup2 .php'));
}
}
/* $sql="SELECT * FROM user WHERE uname='$uname' LIMIT 1";
$result=mysqli_query($conn,$sql);
$countu= mysqli_num_rows($result);
$sql="SELECT * FROM user WHERE email='$email' LIMIT 1";
$result=mysqli_query($conn,$sql);
$counte = mysqli_num_rows($result);
if($counte==1 && $countu==1)
{
$uerr="USER NAME already taken";
$emailerr="email already taken";
$_SESSION['fullname']=$fullname;
$_SESSION['field']=$field;
$_SESSION['emailerr']=$emailerr;
$_SESSION['uerr']=$uerr;
echo "in bothlerr";
die(header('Location:signup1.php'));
}
elseif($counte==1)
{
$emailerr="email already taken";
$_SESSION['fullname']=$fullname;
$_SESSION['field']=$field;
$_SESSION['name']=$uname;
$_SESSION['emailerr']=$emailerr;
$_SESSION['email']='';
echo "in boeerr";
die(header('Location:signup1.php'));
}
elseif($countu==1)
{
$uerr="USER NAME already taken";
$_SESSION['fullname']=$fullname;
$_SESSION['field']=$field;
$_SESSION['email']=$email;
$_SESSION['uerr']=$uerr;
$_SESSION['name']='';
echo "in uerr";
die(header('Location:signup1.php'));
}
else{
if($ngo="ngo"){
date_default_timezone_set("Asia/Kolkata");
$date=date("Y-m-d h:i:s");
$sql="INSERT INTO user(uname,email,password,dtime,full_name,field) VALUES ( '$uname', '$email', '$password','$date','$fullname','$field')";
mysqli_query($conn,$sql);
echo "in ngo data inserted";
}
else{
date_default_timezone_set("Asia/Kolkata");
$date=date("Y-m-d h:i:s");
$field='none';
$sql="INSERT INTO user(uname,email,password,dtime,full_name,field) VALUES ( '$uname', '$email', '$password','$date','$fullname','$field')";
mysqli_query($conn,$sql);
echo "in ind datainserted";
}
}*/
}
?>
and last one is main signup.html file in which javascript works well.
i want to perform some error checking that is why i have saved it as
signup2.php in htdocs
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="signup.css">
</head>
<body onload="form.reset();"">
<div class="container">
<div id="grad">
<ul>
<li style="">Helping Hands...</li>
<li style="float:right"><a class="active" href="#about"> Have an account? Log in</a></li>
</ul>
</div>
<form name=form action="#" onsubmit="return validate()" autocomplete=on method="post">
<div class="outsidebox" >
<div class='login'>
<h2>Register</h2>
<div class="agree1">
<label style="margin-left: 30px;"> <input id="ngo" type="radio" name="option" value="ngo" checked>NGO</label>
<label style="margin-left:30px;"><input id="ind" type="radio" name="option" value="ind">INDIVIDUAL</label>
</div>
<span><input name='username' placeholder='Username' type='text'>
<p id="username" style="font-size: 12px;color:red;"></p>
</span>
<span><input name='email' placeholder='E-Mail Address' type='text'>
<p id="email" style="font-size: 12px;color:red;"></p></span>
<span> <input name='password' placeholder='Password' type='password'>
<p id="password" style="font-size: 12px;color:red;"></p></span>
<span><input name='passwordcon' placeholder=' Confirm Password' type='password'>
<p id="passwordcon" style="font-size: 12px;color:red;"></p></span>
<span><input name='fullname' placeholder='Enter Your Full Name ' type='text'>
<p id="fullname" style="font-size: 12px;color:red;"></p></span>
<div id="a1" >
<strong>PLEASE SELECT FIELDS</strong><br>
<div class="fields">
<select name="fields" id="fields">
<option value="child">Child Welfare</option>
<option value="education">Child Education</option>
<option value="relief">Disaster Management and relief</option>
<option value="envir">Environment</option>
<option value="animals">Animals</option>
</select>
</div>
</div>
<div class='agree'>
<input id='agree' name='agree' type='checkbox'>
<label for='agree'></label>Accept rules and conditions
</div>
<input class='animated' type='submit' value='Register'>
<a class='forgot' href='#'>Already have an account?</a>
</div>
</div>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ngo").click(function(){
$("#a1").show();
});
$("#ind").click(function(){
$("#a1").hide();
});
});
</script>
<script language="javascript">
function validate(){
var flag=1;
var form=document.forms.form;
var user=form.username.value;
if(user==null || user==""){
user="please enter username";
document.getElementById("username").innerHTML=user;
flag=0;
}
else{
document.getElementById("username").innerHTML="";
}
var email=form.email.value;
if(email==null ||email==""){
email="please enter email";
document.getElementById("email").innerHTML=email;
flag=0;
}
else{
document.getElementById("email").innerHTML="";
}
var password=form.password.value;
if(password==null || password==""){
password="please enter password";
document.getElementById("password").innerHTML=password;
flag=0;
}
else{
document.getElementById("password").innerHTML="";
}
var passwordcon=form.passwordcon.value;
if(passwordcon==null || passwordcon==""){
passwordcon="please conform password";
document.getElementById("passwordcon").innerHTML=passwordcon;
flag=0;
}
else{
document.getElementById("passwordcon").innerHTML="";
}
if(passwordcon!=password){
passwordcon =" pasword confirmation fail";
document.getElementById("passwordcon").innerHTML=passwordcon;
flag=0;
}
else{
document.getElementById("passwordcon").innerHTML="";
}
var fullname=form.fullname.value;
if (fullname==null || fullname=="") {
fullname="Enter full name";
document.getElementById("fullname").innerHTML=fullname;
flag=0;
}
else{
document.getElementById("fullname").innerHTML="";
}
if(flag==0){
return false;
}
else{
return true;
}
}
</script>
</html>
You need to clean up your code and format your HTML properly before proceeding with troubleshooting should you still not be able to achieve your intended purpose after this exercise.
As pointed out in comments below your initial post, you code contains lots of problems and need to be well formed;
Your </head> element should have a <title> instance.
You should have <body onload="form.reset();"> (without the extra double quotes at the end, after the semi-column).
Remember to close your <div class="container">; it's currently not.
Your <p> elements should not be child elements of <span> as this is actually not allowed according to your declared document type definition, <!DOCTYPE html>.... more details here, for <p>, and here, for <span>.
Close your <body> tag right before your </html>; not after </form>.
Your JavaScript contents are still part of your page content and as such should be within the opened and closed body tag if not declared in your head section.
Feel free to omit the language="javascript" attribute on your <script> element; it's obsolete.
I created a html form and a function validateForm() to validate the form fields. However the function is only reporting issues with wrong email input, and its not validating the other fields in the form. Can you check my code to see if i have any errors.
Thanks
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Support Center</title>
<meta charset="utf-8">
<link rel="stylesheet" href="styles/layout.css" type="text/css">
<link rel="stylesheet" href="styles/Form.css" type="text/css">
<script type="text/javascript" src="Form.js"></script>
</head>
<body>
<div class="wrapper row1">
<header id="header" class="clear">
<div id="hgroup">
<h1>Support Center</h1>
<h2>Welcome to our website</h2>
</div>
<nav>
<ul>
<li>Home</li>
<li>Our Staff</li>
<li>Location</li>
<li>Help</li>
<li class="last"></li>
</ul>
</nav>
</header>
</div>
</body>
<!-- content -->
<body>
<h1>Help is here!</h1>
<form>
<h1>Should you need assistance, please do not hesitate to contact us:</h1>
<div class="contentform">
<div id="sendmessage"> Your form has been sent successfully. Thank you. </div>
<div class="leftcontact">
<div class="form-group">
<p>Surname<span>*</span></p>
<span class="icon-case"><i class="fa fa-male"></i></span>
<input type="text" name="lastName" id="lastName"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>First Name <span>*</span></p>
<span class="icon-case"><i class="fa fa-user"></i></span>
<input type="text" name="firstName" id="firstName"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>E-mail <span>*</span></p>
<span class="icon-case"><i class="fa fa-envelope-o"></i></span>
<input type="email" name="emailAddress" id="emailAddress"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Office <span>*</span></p>
<span class="icon-case"><i class="fa fa-location-arrow"></i></span>
<input type="text" name="office" id="office"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Desk <span>*</span></p>
<span class="icon-case"><i class="fa fa-map-marker"></i></span>
<input type="text" name="deskNumber" id="deskNumber"/>
<div class="validation"></div>
</div>
</div>
<div class="rightcontact">
<div class="form-group">
<p>Phone number <span>*</span></p>
<span class="icon-case"><i class="fa fa-phone"></i></span>
<input type="text" name="mobilePhone" id="mobilePhone"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Job Number <span>*</span></p>
<span class="icon-case"><i class="fa fa-building-o"></i></span>
<input type="text" name="jobNumber" id="jobNumber"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Computer <span>*</span></p>
<span class="icon-case"><i class="fa fa-info"></i></span>
<input type="text" name="computerNumber" id="computerNumber"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Problem <span>*</span></p>
<span class="icon-case"><i class="fa fa-comment-o"></i></span>
<select name="Problem">
<option value="New User">New User</option>
<option value="Delete User">Delete User</option>
<option value="Lost File">Lost File</option>
<option value="New Software Installation">New Software Installation</option>
<option value="Virus Checking">Virus Checking</option>
</select>
<div class="validation"></div>
</div>
<div class="form-group">
<p>A little about your problem <span>*</span></p>
<span class="icon-case"><i class="fa fa-comments-o"></i></span>
<textarea name="message" rows="14"></textarea>
<div class="validation"></div>
</div>
</div>
</div>
<button type="submit" class="bouton-contact">Send</button>
</form>
</body>
</html>
</body>
</html>
Code
function validateForm() {
var letters = "[A-Za-z]+$";
var numbers = "^[0-9]+$";
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var jobNumber = document.getElementById("jobNumber").value;
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var mobilePhone = document.getElementById("mobilePhone").value;
var emailAddress = document.getElementById("emailAddress").value;
var officeNumber = document.getElementById("office").value;
var deskNumber = document.getElementById("deskNumber").value;
var computerNumber = document.getElementById("computerNumber").value;
if(jobNumber != "" && firstName != "" && lastName != "" && mobilePhone != "" && emailAddress != "" && officeNumber != "" && deskNumber != "" && computerNumber != "") {
if(jobNumber.length == 5 && jobNumber.match(numbers)) {
if(firstName.match(letters) && lastName.match(letters)) {
if(mobilePhone.length == 10 && mobilePhone.match(numbers)) {
if(emailAddress.match(emailReg)) {
alert("Form submitted!");
return true;
}
else {
alert("Please enter a valid email");
return false;
}
}
else {
alert("Please enter a valid mobile number");
return false;
}
}
else {
alert("Please enter a valid first name and last name");
return false;
}
}
else {
alert("Please enter a valid job number");
return false;
}
}
else {
alert("Please enter in all fields");
return false;
}
}
Edit: I just noticed you're using a class contentform and I thought it was an id. I would also add an id to your form to be able to retrieve all form data with one DOM traversal instead of several.
Also, the reason the email is the only one working is because the browser is validating the email without using your JS.
First I would ditch all the variables declared and replace it with the form object.
var formObject = document.getElementById('contentform');
Then you could check whatever child elements that are required. I would also remove the nesting of your if statements, and instead of alerting an error and returning false, add the error to an array to store each one, then return after all items are validated.
var errorList = [];
var isValid = true;
if(formObject.jobNumber == "") {
errorList.push('Please enter a valid job number');
isValid = false;
}
Then rinse and repeat for each element required. After that, just return the list and status (isValid).
// this should be on its own at the bottom of your function right before you return
if (!isValid) {
alert(errorList);
// I would add some formatting or preferably display in the form view.
}
return isValid;
html file
// add the event handler here
<button type="submit" onclick="validateForm()" class="bouton-contact">Send</button>
Also, these
if (!isValid) {
alert(errorList);
}
should be removed from each if statement and placed at the bottom after all have been checked.
Here you validate your email address: First pass the id to javascript by post method then the function validation() will works.
//html
<div>
<input type="text" name="email" id="email" class="" data-wow-delay=".5s" value="" placeholder="Email..." />
</div>
<span id="emailerror" style="display:none; color:#F00">Enter valid email id*</span>
<input type="submit" onClick="return validation();" class="wow fadeInUp" value="Send" />
//javascript
function validation()
{
var email = document.getElementById('email').value;
if(email == '' || !(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)))
{
document.getElementById('emailerror').style.display = 'inline';
var error=1;
}
else
{
document.getElementById('emailerror').style.display = 'none';
}
if(error == 1)
{
return false;
}
else
{
return true;
}
}
now your email validation works fine, thanks
I am trying to execute the mysql query using PHP form. Below is the form
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="signup.css" type="text/css">
<script type="text/javascript" src="form_val.js"></script>
<title>Untitled Document</title>
</head>
<body bgcolor="#0ca3d2">
<div align="right">
<h2>Go back</h2>
</div>
<div class="form-style-10">
<h1>Sign Up Now!<span>Sign up and tell us what you think of the site!</span></h1>
<form action="#" method="post" name="myForm" onSubmit="CheckTerms()">
<div class="section"><span>1</span>First Name & Address</div>
<div class="inner-wrap">
<input type="text" name="First_Name" placeholder="Enter First Name" id="fname">
<label id="error" style="color:red"></label>
<input type="text" name="Last_Name" placeholder="Enter last Name"/>
<label id="error_l" style="color:red"></label>
<select name="gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
<div class="section"><span>2</span>Email </div>
<div class="inner-wrap">
<input type="text" name="Email_i" placeholder="enter email here" id="e_mail" />
<label id="error_e" style="color:red"></label>
<button type="button" name="validate" onclick="loadDoc(this.value)">Validate</button>
<div id="check"></div></div>
<div class="section"><span>3</span>Passwords</div>
<div class="inner-wrap">
<input type="password" name="pass" placeholder="Must be 6 to 15 characters" id="Pass" onBlur="PassCheck()" />
<label id="error_p" style="color:red"></label>
<input type="password" name="repass" placeholder="Retype Password" id="RePass"/>
<label id="error_rp" style="color:red"></label>
<span class="privacy-policy">
<input type="checkbox" name="terms" value="value1" id="check_box">Agree to Terms and Conditions
</span>
<input type="submit" name="signup" value="Register" id="sub_button">
<label id="error_lable" style="color:red"></label>
</div>
</form>
</div>
</body>
I have the below form validation in Javascript,
function CheckTerms(){
var letter = /^[a-zA-Z ]*$/;
if(document.myForm.First_Name.value.match(letter) && document.myForm.First_Name.value =="")
{
document.getElementById("error").innerHTML = "* Please Provide First Name";
document.myForm.First_Name.focus();
return false;
}
if(document.myForm.Last_Name.value.match(letter) && document.myForm.Last_Name.value =="" )
{
document.getElementById("error_l").innerHTML = "* Please provide your Last name!";
document.myForm.Last_Name.focus() ;
return false;
}
var email =/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if(document.myForm.Email_i.value.match(email) && document.myForm.Email_i.value=="")
{
document.getElementById("error_e").innerHTML = "* Please provide your EMAIL!";
document.myForm.Email_i.focus() ;
return false;
}
var min = 6;
var max = 15;
if(document.myForm.pass.value.length < min || document.myForm.pass.value.length > max)
{
document.getElementById("error_p").innerHTML = "Password Should be betweeen 6 to 15 characters";
document.myForm.pass.focus() ;
return false;
}
var pass = document.getElementById("Pass").value;
var re = document.getElementById("RePass").value;
if(pass != re)
{
document.getElementById("error_rp").innerHTML = "Password do not match";
return false;
}
if(document.getElementById("check_box").checked == false)
{
document.getElementById("error_lable").innerHTML = "Please Check";
return false;
}}
<?php
session_start();
include "config.php";
if(isset($_POST['signup']))
{
// my logic here
}
?>
but the problem is, even the javascript returns the error, clicking the submit button , executes PHP script resulting the data entry into database. I want to stop form submission if any of the javascript error exists.
You are not returning the boolean in the event even though you are doing it in the function. onSubmit receives true by default and submits it.
Change
onsubmit="CheckTerms()"
to
onsubmit="return CheckTerms()"
i have one form like this.
<form method="post" action="contact-post.php" id="contact_form" name="contactForm">
<div class="left_form">
<div>
<span><label>NAME</label></span>
<div id='name_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="name" id="name" type="text" class="textbox"></span>
</div>
<div>
<span><label>E-MAIL</label></span>
<div id='email_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="email" id="email" type="text" class="textbox" required></span>
</div>
<div>
<span><label>PHONE</label></span>
<div id='phone_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="phone" id="phone" type="text" class="textbox"></span>
</div>
</div>
<div class="right_form">
<div>
<span><label>SUBJECT</label></span>
<div id='message_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><textarea name="message" id="message" required> </textarea></span>
</div>
<div id='mail_success' class='success' style="background-color:#BFD6BF;text-align:center;margin-bottom:5px;">Your message has been sent successfully.</div>
<div id='mail_fail' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Sorry, error occured this time sending your message.</div>
<div id="submit">
<span><input type="submit" id="send_message" name="submit" value="Submit" class="myButton"></span>
</div>
</div>
</form>
and i call one .js file for it is.
$(document).ready(function(){
$('#send_message').click(function(e){
//Stop form submission & check the validation
e.preventDefault();
// Variable declaration
var error = false;
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#phone').val();
var message = $('#message').val();
// Form field validation
if(name.length == 0){
var error = true;
$('#name_error').fadeIn(500);
}else{
$('#name_error').fadeOut(500);
}
if(email.length == 0 || email.indexOf('#') == '-1'){
var error = true;
$('#email_error').fadeIn(500);
}else{
$('#email_error').fadeOut(500);
}
if(subject.length == 0){
var error = true;
$('#phone_error').fadeIn(500);
}else{
$('#phone_error').fadeOut(500);
}
if(message.length == 0){
var error = true;
$('#message_error').fadeIn(500);
}else{
$('#message_error').fadeOut(500);
}
// If there is no validation error, next to process the mail function
if(error == false){
// Disable submit button just after the form processed 1st time successfully.
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
/* Post Ajax function of jQuery to get all the data from the submission of the form as soon as the form sends the values to email.php*/
$.post("contact-post.php", $("#contact_form").serialize(),function(result){
//Check the result set from email.php file.
if(result == 'sent'){
//If the email is sent successfully, remove the submit button
$('#submit').remove();
//Display the success message
$('#mail_success').fadeIn(500);
}else{
//Display the error message
$('#mail_fail').fadeIn(500);
// Enable the submit button again
$('#send_message').removeAttr('disabled').attr('value', 'Send The Message');
}
});
}
});
});
and one contact-post.php file is.
<?php
include('config.php');
if (isset($_POST['submit'])) {
$name=$_POST['name'];
$mail=$_POST['email'];
$phone=$_POST['phone'];
$msg=$_POST['message'];
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
test_input($name);
$query="INSERT INTO `inquiry` (id,name,contact,email,query) values ('','$name','$phone','$mail','$msg')";
$qur=mysql_query($query);
if ($qur) {
echo 'sent';
}
else {
echo 'failed';
}
}
?>
my problem is when i refresh page it's displaying like this.
i want that all message should not display before clicking submit button.please help me.
Update (adding snippet) :
.error , .success
{
display:none;
}
<form method="post" action="contact-post.php" id="contact_form" name="contactForm">
<div class="left_form">
<div>
<span><label>NAME</label></span>
<div id='name_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="name" id="name" type="text" class="textbox"></span>
</div>
<div>
<span><label>E-MAIL</label></span>
<div id='email_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="email" id="email" type="text" class="textbox" required></span>
</div>
<div>
<span><label>PHONE</label></span>
<div id='phone_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="phone" id="phone" type="text" class="textbox"></span>
</div>
</div>
<div class="right_form">
<div>
<span><label>SUBJECT</label></span>
<div id='message_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><textarea name="message" id="message" required> </textarea></span>
</div>
<div id='mail_success' class='success' style="background-color:#BFD6BF;text-align:center;margin-bottom:5px;">Your message has been sent successfully.</div>
<div id='mail_fail' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Sorry, error occured this time sending your message.</div>
<div id="submit">
<span><input type="submit" id="send_message" name="submit" value="Submit" class="myButton"></span>
</div>
</div>
</form>
You can do one of the following :
Set the error and success classes display to none, since they will be displayed using the fadeIn function.
.error , .success
{
display:none;
}
Or
You can hide the <div>s with jQuery on load as follows :
$(document).ready(function(){
$('.error , .success').hide();
.....
});
I guess the first solution would be a better approach since the elements will not view at all since CSS loads before JS (assuming that this is the order you are loading your files with), while in the second approach the elements will be visible until jQuery loads and hides them.
Add a style as below to hide the error/success messages.
#mail_fail, #mail_success{
display : none;
}