i am having this problem where those validation stopped working starting from the email validation part onwards.
i just couldn't figure out why even after days looking at it and just wondering if someone can point out my mistake here?
Javascript part:
function validateForm()
{
var x=document.forms["myForm"]["firstname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
var x=document.forms["myForm"]["lastname"].value;
if (x==null || x=="")
{
alert("Last name must be filled out");
return false;
}
var x=document.forms["myForm"]["age"].value;
if (x==null || x=="" || x < 18 || x > 110 || isNaN(x))
{
alert("Age must be 18-110");
return false;
}
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length)
{
alert("Not a valid e-mail address");
return false;
}
var x=document.forms["myForm"]["phone"].value;
var pattern = /^\(?([0-9]{2})\)?[ ]+([0-9]{4})[ ]+([0-9]{4})$/;
if (x==null || x=="")
{
alert("Not a valid phone number");
return false;
} else if (x.match(pattern)) {
return true;
} else {
alert ("Phone number must be in the following format: xx xxxx xxxx");
return false;
}
}
and this is the form part:
<form id="myForm" action="../includes/create-user.php" onsubmit="return validateForm();" method="post">
<div id = "table">
<table>
<tr>
<td>First Name: </td>
<td><input type="text" name="firstname" id="firstname"/></td>
</tr>
<tr>
<td>Last Name: </td>
<td><input type="text" name="lastname" id="lastname"/></td>
</tr>
<tr>
<td>Age: </td>
<td><input type="text" name="age" id="age"/></td>
</tr>
<tr>
<td>E-mail (username): </td>
<td><input type="text" name="user" id="user1"/></td>
</tr>
<tr>
<td>Password: </td>
<td><input type="password" name="pass" id="pass1"/></td>
</tr>
<tr>
<td>Phone: </td>
<td><input type="text" name="phone" id="phone"/></td>
</tr>
</table>
</div>
<div>
<input type="submit" name="submit" id="submit" value="Register"/>
</div>
</form>
The first thing that stands out is that you specify your field:
<td><input type="text" name="user" id="user1"/></td>
with id = 'user1'
and you look in your script for email
var x=document.forms["myForm"]["email"].value;
Related
Good evening,
I currently have a HTML Form with a script to validate the field have data entry into them however after it validating all fields are filled it doesnt submit, can anybody please advise what is wrong? New to this so learning and would really appreciate any help possible.
I have attached the code im using below.
<div id="form">
<form name="contact" method="post" action="contact.php" onsubmit="return !!(validatename()&validateemail()&validatecomments()&validateRecaptcha());">
<table width="450px">
<tr>
<td valign="top"><label for="name">Name</label></td>
<td valign="top"><input type="text" name="name" maxlength="50" size="30"></td>
</tr>
<tr>
<td valign="top"><label for="email">Email Address</label></td>
<td valign="top"><input type="text" name="email" maxlength="80" size="30"></td>
</tr>
<tr>
<td valign="top"><label for="comments">Comments</label></td>
<td valign="top"><textarea name="comments" maxlength="1000" cols="32" rows="8"></textarea></td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<div id="form" class="g-recaptcha" data-sitekey="6LdcZFkUAAAAAFoHAYtupqKzCgd2T9XzHZFj8XNw"></div>
<input type="image" src="images/submit.png" alt="Submit">
</td>
</tr>
</table>
</form>
<script>
function validatename()
{
if( document.contact.name.value == "" )
{
alert( "Please provide your name!" );
document.contact.name.focus() ;
return false ;
}
}
function validateemail()
{
if( document.contact.email.value == "" )
{
alert( "Please provide your email address!" );
document.contact.email.focus() ;
return false ;
}
}
function validatecomments()
{
if( document.contact.comments.value == "" )
{
alert( "Please provide your comments!" );
document.contact.comments.focus() ;
return false ;
}
}
function validateRecaptcha() {
var response = grecaptcha.getResponse();
if (response.length === 0) {
alert("You need to fill the captcha");
return false ;
}
}
</script>
This is one way how you could do it:
function validatename() {
if (document.contact.name.value == "") {
alert("Please provide your name!");
document.contact.name.focus();
return false;
}
else {
return true;
}
}
function validateemail() {
if (document.contact.email.value == "") {
alert("Please provide your email address!");
document.contact.email.focus();
return false;
}
else {
return true;
}
}
function validatecomments() {
if (document.contact.comments.value == "") {
alert("Please provide your comments!");
document.contact.comments.focus();
return false;
}
else {
return true;
}
}
function validateRecaptcha() {
var response = grecaptcha.getResponse();
if (response.length === 0) {
alert("You need to fill the captcha");
return false ;
}
else {
return true;
}
}
document.getElementById('my-form').addEventListener('submit', function(e) {
e.preventDefault();
if (validatename() && validateemail() && validatecomments() && validateRecaptcha()) {
var formValidation = true;
}
else {
var formValidation = false;
}
if (formValidation) {
this.submit();
}
});
<div id="form">
<form id="my-form" name="contact" method="post" action="contact.php">
<table width="450px">
<tr>
<td valign="top"><label for="name">Name</label></td>
<td valign="top"><input type="text" name="name" maxlength="50" size="30"></td>
</tr>
<tr>
<td valign="top"><label for="email">Email Address</label></td>
<td valign="top"><input type="text" name="email" maxlength="80" size="30"></td>
</tr>
<tr>
<td valign="top"><label for="comments">Comments</label></td>
<td valign="top"><textarea name="comments" maxlength="1000" cols="32" rows="8"></textarea></td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<div id="form" class="g-recaptcha" data-sitekey="6LdcZFkUAAAAAFoHAYtupqKzCgd2T9XzHZFj8XNw"></div>
<input type="image" src="images/submit.png" alt="Submit">
</td>
</tr>
</table>
</form>
</div>
To make it work correctly, make sure that grecaptcha is defined.
Hi and sorry for my bad English
I have a contact page and i am using javascript to make a "captcha". so peaople must make a math and if thats correct they can send me a e-mail. Now my problem is that javasctipt give a alert that the math is wrong or not filled but the e-mail is still seended.
my html:
<script type="text/javascript">
function validate () {
var ta = document.getElementById("ta").value;
var answer = document.getElementById("answer").value;
var digit1 = parseInt(document.getElementById("digit1").innerHTML);
var digit2 = parseInt(document.getElementById("digit2").innerHTML);
var sum = digit1+ digit2;
if (answer === null || answer === "") {
alert("reken de cijfers uit");
return false;
} else if (answer != sum){
alert("je som is fout");
} else if (ta === null || ta === ""){
alert("schrijf een bericht");
} else {
document.getElementById("answer").innerHTML = "bezig met sturen";
document.getElementById("answer").innerHTML = "";
}
}
function randNums () {
var rand_num1 = Math.floor(Math.random()*10)+1;
var rand_num2 = Math.floor(Math.random()*10)+1;
document.getElementById("digit1") .innerHTML=rand_num1;
document.getElementById("digit2") .innerHTML=rand_num2;
}
</script>
<body onload="randNums() ;">
<form action="/cgi-bin/form.cgi" method="POST" onsubmit="return validate ();">
<input type="hidden" name="DEBUG" value="0">
<input type="hidden" name="MAILFILE" value="peymankarimi/form/sjabloon.txt">
<input type="hidden" name="MAILTO" value="peyman_50#hotmail.com">
<input type="hidden" name="REPLYFAULT" value="peymankarimi/form/formulier.html">
<input type="hidden" name="REPLYOK" value="peymankarimi/form/verzonden.html">
<table border="0" width="374" id="contactformulier">
<tr>
<td width="137">Naam:</td>
<td width="230"><input type="text" size="31" name="naam" placeholder="Naam"></td>
</tr>
<tr>
<td width="137">Voornaam:</td>
<td width="230"><input type="text" size="31" name="voornaam" placeholder="Voornaam"></td>
</tr>
<tr>
<td width="137">Woonplaats:</td>
<td width="230"><input type="text" size="31" name="woonplaats" placeholder="Woonplaats"></td>
</tr>
<tr>
<td width="137">Telefoonnummer:</td>
<td width="230"><input type="text" size="31" name="telefoon" placeholder="Telefoonnummer"> </td>
</tr>
<tr>
<td width="137">E-mailadres: <br></br></td>
<td width="230">
<input type="text" size="31" name="MAILFROM" placeholder="E-mailadres"> <br></br> </td>
</tr>
</tr>
<tr>
<td width="137">Onderwerp:</td>
<td width="230"><input type="text" size="31" maxlength="30" name="SUBJECT"> </td>
</tr>
<tr>
<td colspan="2">Uw vragen, opmerkingen, suggesties, ... :<br>
<textarea id="ta" name="omschrijving" rows="6" cols="43" ></textarea>
<br />
<strong> Tel deze cijfers op </strong>
<span id="digit1"> </span> +
<span id="digit2"> </span> =
<input type="text" id="answer" size="2"; />
<br />
<p align="right"><input type="submit" name="cmdVerzenden" value="Verzenden">
<input type="reset" name="cmdWissen" value="Wissen"></td>
</form>
</tr>
</table>
</form>
</body>
Your validate function needs to return false on all errors to stop the form from submitting. You only seem to have it for one error.
function validate () {
var ta = document.getElementById("ta").value;
var answer = document.getElementById("answer").value;
var digit1 = parseInt(document.getElementById("digit1").innerHTML);
var digit2 = parseInt(document.getElementById("digit2").innerHTML);
var sum = digit1+ digit2;
if (answer === null || answer === "") {
alert("reken de cijfers uit");
return false;
} else if (answer != sum){
alert("je som is fout");
return false;
} else if (ta === null || ta === ""){
alert("schrijf een bericht");
return false;
} else {
document.getElementById("answer").innerHTML = "bezig met sturen";
document.getElementById("answer").innerHTML = "";
}
}
I would need a little help of you today, i'm wondering how can i validate my script for letters only on first 2 inputs?
I'm using javascript to validate my form below: I have managed to validate for email though and zip (numbers only)...
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
function checkForEmail()
{
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Alert")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Alert" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.Surname.value == "" )
{
alert( "Alert" );
document.myForm.Surname.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Alert" );
document.myForm.EMail.focus() ;
return false;
}else{
var ret = checkForEmail();
if( ret == false )
{
return false;
}
}
if( document.myForm.zip.value == "" ||
isNaN( document.myForm.zip.value ) ||
document.myForm.zip.value.length != 13 )
{
alert( "Alert" );
document.myForm.zip.focus() ;
return false;
}
return( true );
}
//-->
</script>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right">Surname</td>
<td><input type="text" name="Surname" /></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td align="right">zip</td>
<td><input type="text" name="zip" /></td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
how can i validate my script for letters only on first 2 inputs
// Check s contains at least one letter and is only letters
function checkLettersOnly(s) {
return /^[a-z]+$/i.test(s);
}
if (!checkLettersOnly(document.myForm.Name.value)) {
// not letters only
}
I wonder if I can execute onlick function only after JS validation any ideas?
I have a form which has e-amil and phone mandatory filed and i would like to check them before form is submitted , even more if everything is ok another div onclick="$('#dialog-links-blocks').show()" should be display with a message Thank you! How can I make it to be shown only after validation !
<script type="text/javascript">// <![CDATA[
function validateForm()
{
var x=document.forms["myform"]["phone"].value;
var y=document.forms["myform"]["email"].value;
if (x==null || x=="")
{
alert("Укажите номер телефона!");
return false;
}
if (y==null || y=="")
{
alert("Укажите email!");
return false;
}
}
// ]]></script>
<iframe name="hiddenFrame" width="320" height="240"></iframe>
<form id="validation" action="http://listovki.md/send_form_email.php" method="POST" name="myform" enctype="multipart/form-data" onsubmit="return validateForm()" target="hiddenFrame">
<table><colgroup> <col width="122" /> <col width="260" /> </colgroup>
<tbody>
<tr>
<td><label>имя</label></td>
<td><input type="text" name="family" /></td>
</tr>
<tr>
<td><label>почта</label></td>
<td><input type="email" name="email" /></td>
</tr>
<tr>
<td><label>gsm</label></td>
<td><input class="gsm" type="tel" name="phone" /></td>
</tr>
<tr>
<td colspan="2"><input class="aplicaAcumBt" onclick="$('#dialog-links-blocks').show()" type="submit" name="submit" value="отправить" /></td>
</tr>
</tbody>
</table>
</form>
Why not show div only if validation is true? why show only on click
<script type="text/javascript">// <![CDATA[
function validateForm()
{
var x=document.forms["myform"]["phone"].value;
var y=document.forms["myform"]["email"].value;
if (x==null || x=="")
{
alert("Укажите номер телефона!");
return false;
}
if (y==null || y=="")
{
alert("Укажите email!");
return false;
}
// Validation is true here
$('#dialog-links-blocks').show()
}
</script>
I have two forms inside my body:
<body>
<form method=post name="signin">
<table>
<theader>Sign In</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 maxlength=25 name=em id=em />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 maxlength=15 name=up id=up />
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" />
</td>
</tr>
</table>
</form>
<br>
<br>
<br>
<br>
<form method=post name="register">
<table>
<theader>Don't have an account? Register, it's Free!</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 name=email id=email /><span id="nameerror"></span>
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 name=pass id=pass />
</td>
</tr>
<tr>
<td>Confirm Password:</td>
<td>
<input type=password length=15 name=cpass id=cpass /><span id="pwerror"></span>
</td>
</tr>
<tr>
<td>Account Type:</td>
<td>
<select id="seltype">
<option name=standard SELECTED>Standard</option>
<option name=admin>Administrator</option>
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" onClick="JavaScript:validate();" />
</td>
</tr>
</table>
</form>
</body>
I would like to do the following:
For each form, validate to ensure it's filled in and also for the second form I want to validate that the two password matched. I have the following:
$( document ).ready(function() {
var t = document.getElementById("email").value;
var y = document.getElementById("seltype").value;
var k = document.getElementById("pass").value;
var j = document.getElementById("cpass").value;
$('#cpass').blur(function(){
if (k != j) {
document.getElementById("pwerror").innerHTML = "Password does not match";
}
else {
document.getElementById("pwerror").innerHTML = "Password matches";
}
});
});
function validate() {
if (t != null && y != null && k != null && j != null) {
}
if (t == "" || y == "" || k == "" || j == "") {
alert("fill in");
}
}
I preferred not to mix native JavaScript and validated using pure jQuery only. One of the benefits here is that the empty field check would work for any <form> since it's not tied to any particular form, input name or ids.
$( document ).ready(function() {
$( 'form' ).submit(function(event) {
var $form = $( this );
var checkPass = true;
$form.find( 'input' ).each(function( i, e) {
if (e.value.length === 0) {
event.preventDefault();
alert(e.name + " cannot be empty");
return (checkPass = false);
}
});
if( checkPass && $form.is( '[name="register"]' ) ) {
if( $form.find( '#pass').val() !== $form.find( '#cpass' ).val()) {
event.preventDefault();
alert( 'Passwords do not match.' );
}
}
});
});
Working Demo at JsFiddle.net
Basics:
If you want to check if a variable is not null, ideally, you should use !== & not !=.
If you want to check if a variable is "", ideally, you should use === and not ==.
Check out: http://www.w3schools.com/js/js_comparisons.asp
Use JSFiddle.net to give a better working example of your code WHICH can help others see a demo of your actual code.
Your code currently has lot of scope for optimization. Since its just a basic validation you are trying to achieve, why do you need to use jQuery? Why not just use JavaScript basic variable comparisons?
Google before you ask here. If its so straightforward, your question will get downvoted.
Alert is not the best way to notify the user to fill in. For example, your 'Password Matches' or 'Password Doesn't Match' div is a much better way to notify the user. Use Form Events to validate the form as the user is already filling in the details in the form!
Question responsibly by giving your exact problems and not just pasting the code! How would we know where you are facing a problem.
Variables work in Scope. Check the scope of variable before using them in different functions. For example, you define var t, y, k, j in first function and use it in second function - will throw up an error of undefined variable t.
From what information you provided, here's what I could help with:
HTML:
<form method=post name="signin">
<table>
<theader>Sign In</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 maxlength=25 name=em id=em />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 maxlength=15 name=up id=up />
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" onclick="javascript:validateSignin()" />
</td>
</tr>
</table>
</form>
<br>
<br>
<br>
<br>
<form method=post name="register">
<table>
<theader>Don't have an account? Register, it's Free!</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 name=email id=email /><span id="nameerror"></span>
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 name=pass id=pass />
</td>
</tr>
<tr>
<td>Confirm Password:</td>
<td>
<input type=password length=15 name=cpass id=cpass /><span id="pwerror"></span>
</td>
</tr>
<tr>
<td>Account Type:</td>
<td>
<select id="seltype">
<option name=standard SELECTED>Standard</option>
<option name=admin>Administrator</option>
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" onClick="JavaScript:validateRegister();" />
</td>
</tr>
</table>
</form>
JS:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function () {
$('#cpass').blur(function () {
if (k != j) {
document.getElementById("pwerror").innerHTML = "Password does not match";
} else {
document.getElementById("pwerror").innerHTML = "Password matches";
}
});
});
function validateRegister() {
var t = document.getElementById("email").value;
var y = document.getElementById("seltype").value;
var k = document.getElementById("pass").value;
var j = document.getElementById("cpass").value;
if (t !== null && y !== null && k !== null && j !== null) {}
if (t === "" || y === "" || k === "" || j === "") {
alert("fill in");
}
}
function validateSignin() {
var se= document.getElementById("em").value;
var sp= document.getElementById("up").value;
if (se !== null && sp !== null){ }
if (se === "" || sp === "") {
alert("fill in");
}
}
</script>
Hope it helps! :)