Validating PHP Form Data Using Java Script - javascript

I am validating php form data using java script, but the form send the data without validating. Am I making any mistake in creating this form validation. HTM code is:
<form name="form1" action="sendmail.php" onSubmit="return validateform1();" method="post">
<table>
<tbody>
<tr><td><input id="name" class="w200" name="name" type="text" value="Your Name" onFocus="if(this.value=='Your Name')this.value=''" onBlur="if(this.value=='')this.value='Your Name'"></td></tr>
<tr><td><input id="cname" class="w200" name="cname" type="text" value="Company Name" onFocus="if(this.value=='Company Name')this.value=''" onBlur="if(this.value=='')this.value='Company Name'"></td></tr>
<tr><td><input class="w200" name="email" type="text" value="Your Email ID" onFocus="if(this.value=='Your Email ID')this,value=''" onBlur="if(this.value=='')this.value='Your Email ID'"></td></tr>
<tr><td><input class="w200" name="mno" type="text" value="Mobile No." onFocus="if(this.value=='Mobile No.')this.value=''" onBlur="if(this.value=='')this.value='Mobile No.'"></td></tr>
<tr><td><input class="w200" name="country" type="text" value="Country" onFocus="if(this.value=='Country')this.value=''" onBlur="if(this.value=='')this.value='Country'"></td></tr>
<tr><td><textarea class="w200n h60" name="message" cols="23" rows="4" onFocus="if(this.value=='Requirements')this.value=''" onBlur="if(this.value=='')this.value='Requirements'">Requirements</textarea></td></tr>
<tr><td><input type="submit" value="Submit"><input name="reset" type="reset" value="Reset"></td></tr>
</tbody>
</table>
</form>
And the java script for this form validation is:
<script language="javascript">
function validateform1() {
if($document.form1.name.value=="") {
alert("Enter Name");
return false;
}
if($document.form1.cname.value=="") {
alert("Please enter company name");
return false;
}
if($document.form1.email.value=="") {
alert("Please enter your email");
return false;
}
if($document.form1.mno.value=="") {
alert("Please enter your mobile no.");
return false;
}
if($document.form1.country.value=="") {
alert("Please enter country");
return false;
}
}
</script>

There's no need to use $ in "$document"
You should use "document" only
This is what you should be try:
<script language="javascript">
function validateform1()
{
if(document.form1.name.value=="")
{
alert("Enter Name");
return false;
}
else if(document.form1.cname.value=="")
{
alert("Please enter company name");
return false;
}
else if(document.form1.email.value=="")
{
alert("Please enter your email");
return false;
}
else if(document.form1.mno.value=="")
{
alert("Please enter your mobile no.");
return false;
}
else if(document.form1.country.value=="")
{
alert("Please enter country");
return false;
}
else
{
return true;
}
}
</script>
and call the validateform1() on "onSubmit" event of the form.

simply do this for all fields, because you already have the value assigned for the input type as Your Name, we need to check if it is either Your name or null
if(document.form1.name.value=="Your Name" || document.form1.name.value=="")

If none of the conditions trigger and return false, you need to return true; at the end before your last closing squiggly bracket ( } ).
To clarify: I would write the function like this:
function validateform1() {
if(document.form1.name.value=="") {
alert("Enter Name");
return false;
}
else if(document.form1.cname.value=="") {
alert("Please enter company name");
return false;
}
else if(document.form1.email.value=="") {
alert("Please enter your email");
return false;
}
else if(document.form1.mno.value=="") {
alert("Please enter your mobile no.");
return false;
}
else if(document.form1.country.value=="") {
alert("Please enter country");
return false;
}
return true;
}

Related

Text obtained with innerHTML dissapear

I have the following code:
function passVerif() {
if (document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
if (document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="button" name="required" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
As you can see, input type is submit. Because of that (page is refreshing after click on button) the text I want to show disappears after refresh.
As I read on other posts, the simple change from submit to button will do the dew.
But I am suspecting that I messed up the return false and return true instructions in all of my functions.
Is this correct? If they are in a logical way I can avoid the page refresh and continue to use submit? At least until all conditions are met and the form is good to go.
In other words, can someone help me to put return false and true in such way that the page will refresh only if all conditions are met.
Thanks a lot, I am not even a noob.
Codes are copied from different sources on the internet. I am at the very beginning of coding road. Please have mercy :)
I would change it to one validation function and have a bool that is returned based on if it has errored or not:
// Just have one validation function
function validate() {
var errorMessage = ''; // build up an error message
var email = document.forms['form'].email.value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (email === "") {
errorMessage += "Email field is empty!<br>";
} else if (!emailFilter.test(email)) { // this can be else if
errorMessage += "Please enter a valid e-mail address!<br>";
}
if (document.forms['form'].pass.value === "") {
errorMessage += "Password field is empty!<br>"
}
if (errorMessage === '') {
return true; // return true as no error message
} else {
document.getElementById('error-message').innerHTML = errorMessage; // show error message and return false
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="submit" name="required" onclick="return validate();">
</form>
</div>
<div id="error-message">
<!-- CAN HAVE ONE ERROR MESSAGE DIV -->
</div>
I tried with your code and I could find the the messages were not getting updated based on the conditions. So I did few modifications to your code to display the message based on which condition fails.
HTML
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br><br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br><br>
<input type="submit" name="required" value="Submit" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
JS
function passVerif() {
messagePV.innerHTML = ("")
if(document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
messageEV.innerHTML = ("")
if(document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
messageV.innerHTML = ("")
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
By initializing the errormessage filed to empty sting u can maintain the fresh set of error messages.
Jsfiddle: https://jsfiddle.net/85w7qaqx/1/
Hope this helps out.

Unable to stop form from submitting with empty inputs

I am unable to stop the form from submitting when any of the inputs are blank. It's not erroring out, but it's also not stopping the submit. I have the function being called in the form submit input. It is under the onClick call.
JS File
function stopSubmit(){
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount == ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}
HTML File
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
Edit
Use the required attribute and you won't even need any JavaScript. See demo 2. for a functioning demo see this PLUNKER
OLD
Before each return false add e.preventDefault()
Demo (Does not function due to SO security measures)
function stopSubmit(e) {
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
e.preventDefault();
return false;
}
if (inType == "Select One") {
alert("Please select a frequency");
e.preventDefault();
return false;
}
if (inAmount == "") {
alert("Please enter an amount");
e.preventDefault();
return false;
} else {
alert("Your form was submitted");
}
}
<form>
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
</form>
Demo 2 Use the required attribute
<!DOCTYPE html>
<html>
<head>
<style>
input {
display: block
}
</style>
</head>
<body>
<form id='inform' action='http://httpbin.org/post' method='post'>
<input id='indate' name='indate' required>
<input id='intype' name='intype' required>
<input id='inamount' name='inamount' required>
<input type="submit">
</form>
</body>
</html>
I was able to see where you doing the mistake, document.getElementById() takes in a string as the parameter but you happen to be passing an undefined variable
function stopSubmit(){
var inDay = document.getElementById('indate').value;
var inType = document.getElementById('intype').value;
var inAmount = document.getElementById('inamount').value;
if (inDay === "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount === ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}

Html Form If statement in OnSubmit Field

I'm fairly new to html/php/js and I'm running into an issue when conditionally submitting my form. Basically, what Im trying to do is have it where the confirm('Do you want to submit this form?') function only shows up if every field has a value entered (the checkform() function). If both are true, then the form will submit. Any help would be greatly appreciated, thanks!
<script type="text/javascript">
function checkform()
{
var myForm=document.frmhot;
if(myForm.status.value==""){
alert("Please select a timeframe status.");
return false;
myForm.status.focus();
}
if (myForm.line.value==""){
alert("Please select a line.");
return false;
}
if(myForm.reason.value==""){
alert("Please select a reason code.");
return false;
}
if(myForm.partnum.value==""){
alert("Please enter a part number.");
return false;
}
if(myForm.badgescan.value==""){
alert("Please enter a badge number.");
return false;
}
return true;
}
</script>
<form method="post" action="newhotpartgenerate.php" name="frmhot"
onclick="if(checkform();){
confirm('Do you want to submit the form?');
}
>
<input class="button_text" type="submit" value="Submit" name="submit" onclick= "checkform();" />
</form>
Complete working solution with corrections and tweaks for IE compatibility to a certain extend.
<script>
function checkform(evt) {
var myForm = document.frmhot;
var condition = true;
if(myForm.status.value==""){
alert("Please select a timeframe status.");
myForm.status.focus();
condition = false;
}
if (myForm.line.value==""){
alert("Please select a line.");
condition = false;
}
if(myForm.reason.value==""){
alert("Please select a reason code.");
condition = false;
}
if(myForm.partnum.value==""){
alert("Please enter a part number.");
condition = false;
}
if(myForm.badgescan.value==""){
alert("Please enter a badge number.");
condition = false;
}
if(condition){ condition = confirm('Do you want to submit the form?'); }
if(!condition) {
if(evt.preventDefault) { event.preventDefault(); }
else if(evt.returnValue) { evt.returnValue = false; }
else { return false; }
}
}
</script>
<form method="post" action="newhotpartgenerate.php" name="frmhot" onsubmit="checkform(event)">
<input type="text" name="status"/>
<input type="text" name="line"/>
<input type="text" name="reason"/>
<input type="text" name="partnum"/>
<input type="text" name="badgescan"/>
<input class="button_text" type="submit" value="Submit"/>
</form>
You have the right idea, just extract your code into its own function and then call that in the onclick.
Add this function:
function checkAndConfirm() {
if(checkform()) {
if (confirm('Do you want to submit the form?')) {
// submit the form
}
}
And then call it from the onclick attribute:
<form method="post" action="newhotpartgenerate.php" name="frmhot" onclick="checkAndConfirm()">

Javascript validation for email making issues

In my project, I am doing a JS validation for registration purpose. But the validation fails after the email validation. Upto the email validation, it works fine. But after that it is not showing any alerts for rest of validation code.
function signup() {
var signupFullName = $("#signup-full-name");
var signupName = $("#signup-login-name");
var signupEmailAddress = $("#signup-email-address");
var signupPhoneNumber = $("#signup-phone-number");
var signupPassword = $("#signup-password");
var signupConfirmPassword = $("#signup-confirm-password");
var signupAcceptTerms = $("#signup-accept-terms");
if (signupFullName[0].value == "" || signupFullName[0].value == null) {
//alert("Please enter a valid full name.");
alert("Please enter your full name");
signupFullName[0].focus();
return false;
} else if (signupName[0].value == "" || signupName[0].value == null) {
//alert("Please enter a valid login name.");
alert("Please enter your login name.");
signupName[0].focus();
return false;
} else if (signupEmailAddress[0].value == "" || signupEmailAddress[0].value == null) {
//alert("Please enter a valid email address.");
alert("Please enter your email address.");
signupEmailAddress[0].focus();
return false;
}
else if(signupEmailAddress[0].value != "") // problem in this section
{
email=signupEmailAddress[0].value;
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(email))
{
alert("Please enter a valid email address.");
signupEmailAddress[0].focus();
return false;
}
}
else if (signupPhoneNumber[0].value == "" || signupPhoneNumber[0].value == null) {
// alert("Please enter a valid phone number.");\
alert("Please enter your phone number.");
signupPhoneNumber[0].focus();
return false;
} else if (signupPassword[0].value == "" || signupPassword[0].value == null) {
//alert("Please enter a valid password.");
alert("Please enter your password.");
signupPassword[0].focus();
return false;
} else if (signupConfirmPassword[0].value == "" || signupConfirmPassword[0].value == null) {
alert("Please confirm the password.");
signupConfirmPassword[0].focus();
return false;
} else if (signupPassword[0].value != signupConfirmPassword[0].value) {
//alert("Please confirm the password.");
alert("Password mismatch");
signupConfirmPassword[0].focus();
return false;
} else if ($("#signup-accept-terms")[0].checked == false) {
alert("Please accept the terms and conditions.");
return false;
} else {
alert("Done");
return false;
}
}
HTML form code:
<form name="signup-form" id="signup-form" method="post" action="<?php echo $site_path; ?>/register" class="form-1" onsubmit="signup();return false;">
<p class="field">
<a href="<?php echo $root_path; ?>">
<img src="<?php echo $theme_path;?>/images/logo.png"/>
</a>
<h4 style="margin-top:10px;color:#208CCD;">Signup</h4>
<br/>
</p>
<p class="field">
<input type="text" name="signup-full-name" id="signup-full-name" placeholder="Full name">
<i class="icon-user icon-large"></i>
</p>
<p class="field">
<input type="text" name="signup-login-name" id="signup-login-name" placeholder="User name">
<i class="icon-signin icon-large"></i>
</p>
<p class="field">
<input type="text" name="signup-email-address" id="signup-email-address" placeholder="Email address">
<i class="icon-inbox icon-large"></i>
</p>
<p class="field">
<input type="text" name="signup-phone-number" id="signup-phone-number" placeholder="Phone number">
<i class="icon-phone icon-large"></i>
</p>
<p class="field">
<input type="password" name="signup-password" id="signup-password" placeholder="Password">
<i class="icon-lock icon-large"></i>
</p>
<p class="field" style="margin-top:10px;">
<input type="password" name="signup-confirm-password" id="signup-confirm-password" placeholder="Confirm password">
<i class="icon-lock icon-large"></i>
</p>
<p class="field">
<input type="checkbox" name="signup-accept-terms" id="signup-accept-terms" style="margin-top:10px;color:#B3B3B3">
I accept the Terms and Conditions and the Privacy Policies
</input>
</p>
<p class="submit">
<button type="submit" name="submit"><i class="icon-arrow-right icon-large"></i></button>
</p>
</form>
Can anyone help me to solve this? Thanks in advance.
As I see it it's because you use if/else to check validity of the fields.
So the code picks one error at a time - if any. While you should have something like a for-loop across all the fields you want to validate
I mean it picks this
} else if(signupEmailAddress[0].value != "") {
but does not fall into inner check anymore
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(email))
because email is ok now
Your problem is this statement:
else if(signupEmailAddress[0].value != "")
Because the email field contains text, this rule is evaluated as true and so the rest of the else if blocks won't be executed.
I'd consider changing the else if's to be individual if statements so that they won't stop each other.
You have to remove the return false statements inside if condition. Inside validation function, at the end you have to return false if any of the validation fails. Here's an example to do it:
var result = true;
if(condition 1){ // if condition 1 fails, make result = false;
}
if(condition 1){ // if condition 2 fails, make result = false;
}
if(condition 1){ // if condition 3 fails, make result = false;
}
return result; // After all validations, result result
That's it.
Replace your correction place with this code....
else if(signupEmailAddress[0].value != "" && !(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(signupEmailAddress[0].value)) // problem in this section
{
alert("Please enter a valid email address.");
signupEmailAddress[0].focus();
return false;
}

Javascript form validation not working due to typos

HTML
<form name="registerForm" action="/user/register.cgi" method="post" onsubmit="validateRegisterForm()">
<table>
<tbody>
<tr>
<td><input type="text" name="firstname" placeholder="First Name"></td>
</tr>
<tr>
<td><input type="text" name="lastname" placeholder="Last Name"></td>
</tr>
<tr>
<td><input type="email" name="email" placeholder="Email"></td>
</tr>
<tr>
<td><input type="password" name="password" placeholder="Password"></td>
</tr>
<tr>
<td><input type="password" name="confirmPassword" placeholder="Confirm Password"></td>
</tr>
<tr>
<td><input type="submit" value="Register Details"></td>
</tr>
</tbody>
</table>
</form>
Javascript
function validateRegisterForm(){
var fname=document["registerForm"]["firstname"].value;
var lname=document["registerForm"]["lastname"].value;
var email=document["registerForm"]["email"].value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
var pass=document["registerForm"]["password"].value;
var passlen = pass.length;
var confpass=document["registerForm"]["cofirmPassword"].value;
if (fname==null || fname=="")
{
alert("Please enter a First Name!");
return false;
}
else if (lname==null || lname=="")
{
alert("Please enter a Last Name!");
return false;
}
else if (email==null || email=="")
{
alert("Please enter a email!");
return false;
}
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid email address!");
return false;
}
else if (pass==null || pass=="")
{
alert("Please enter a Password!");
return false;
}
else if (6<=passlen<=15)
{
alert("Password needs to be to have a lenght of 6-15!");
return false;
}
else if (pass!=confpass)
{
alert("Passwords do not match!");
return false;
}
}
There are some errors in your code
cofirmPassword should be confirmPassword
should be
var confpass=document["registerForm"]["confirmPassword"].value;
Instead of
var confpass=document["registerForm"]["cofirmPassword"].value;
UPDATE
Your mistakes are
x.length should be email.length
(6<=passlen<=15) should be (passlen < 6 || passlen > 15)
Your updated working DEMO
Today, in the times of HTML5, it's preferable to use the new validation mechanisms built into the browsers. A general approach is to define a constraint checking function per property (preferably in the model class in a JavaScript-based MVC app, like User.checkEmail) and assign it via HTML5's setCustomValidity function as an event listener for input events to the input field elements, so the user gets immediate validation feedback on user input, like in
emailInpEl.addEventListener("input", function () {
emailInpEl.setCustomValidity( User.checkEmail( emailInpEl.value).message);
});
So, whenever the string represented by the expression User.checkEmail(emailInpEl.value).message is empty, everything is fine. Otherwise, if it represents an error message, the browser indicates the constraint violation to the user by marking the form field concerned (typicallly with a red border) and by displaying the error message.
You can read more on using the programmatic HTNL5 validation techniques in this tutorial.
your JavaScript Code is wrong try this one
function validateRegisterForm(){
var fname=document.getElementByName["registerForm"][0].value;
var lname=document.getElementByName["registerForm"][0].value;
var email=document.getElementByName["registerForm"][0].value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
var pass=document.getElementByName["registerForm"][0].value;
var passlen = pass.length;
var confpass=document.getElementByName["registerForm"][0].value;
if (fname==null || fname=="")
{
alert("Please enter a First Name!");
return false;
}
else if (lname==null || lname=="")
{
alert("Please enter a Last Name!");
return false;
}
else if (email==null || email=="")
{
alert("Please enter a email!");
return false;
}
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid email address!");
return false;
}
else if (pass==null || pass=="")
{
alert("Please enter a Password!");
return false;
}
else if (6<=passlen<=15)
{
alert("Password needs to be to have a lenght of 6-15!");
return false;
}
else if (pass!=confpass)
{
alert("Passwords do not match!");
return false;
}
}

Categories

Resources