I'm trying to validate fields in a form using JavaScript. The fields should be validated either when the user leaves a field (onblur) and when the user presses submit. The form should not be sent if the validation fails in any way on a required field.
The thing is I also have a JS function that if validation succeeds, should rewrite one of the fields that is validated, and send the form.
This is my HTML:
<head>
<meta charset='UTF-8'>
<script type="text/javascript" src="./library/checkcreateuser.js"></script>
<script type="text/javascript" src="./library/hashcreateuser.js"></script>
</head>
<body>
<div class="maindiv">
<form name="createform" id="createform" onsubmit="return formhash();" action="#" method="post">
<input type="text" name="email" id="email" onblur="checkEmail()" placeholder="E-postadress" maxlength="50" />
<label for="email" id="labemail"></label><br />
<input type="text" name="testemail" id="testemail" onblur="checkEmailConfirm()" placeholder="Bekräfta e-postadress" maxlength="50" /><br />
<label for="testemail" id="labtestemail"></label><br />
<br />
... other input fields that should be validated, not yet written ...
<br />
<input type="password" name="password" id="password" placeholder="Lösenord" maxlength="50" /><br />
<label for="password" id="labpassword"></label><br />
<input type="password" name="testpassword" id="testpassword" placeholder="Bekräfta lösenord" maxlength="50" /><br />
<label for="testpassword" id="labtestpassword"></label><br />
<br />
<input type="submit" placeholder="Registrera" onclick="validateForm()"><br />
</form>
</div>
</body>
And this is my javascript for validation:
function checkEmail() {
var validemail = true;
var email = document.getElementById("email");
var divided = email.split("#");
var divlen = divided.length;
if (divlen != 2) {
validemail = false;
document.getElementById("labemail").innerHTML = "Felaktig e-postadress";
} else {
document.getElementById("labemail").innerHTML = "<font color='#00cc00'>Korrekt epostadress</font>";
}
// More code to validate Email to come
return validemail;
}
function checkEmailConfirm() {
var validtestemail = true;
var email = document.getElementById("email");
var testemail = document.getElementById("email");
if (testemail != email) validtestemail = false;
return validtestemail;
}
function validateForm() {
var validform = true;
var returnval = true;
validform = checkEmail();
if (validform == false) returnval = false;
validform = checkEmailConfirm();
if (validform == false) returnval = false;
return returnval;
}
My problem is that nothing happens when i leave the email- or testemail-fields.
My second question is, if I want the form not submitted if any of the validations fails, but submitted and also hashed using the function called formhash() if the validations succeeds, is this the correct way?
EDIT: Using the Chrome debugger, i have the following errors:
Uncaught TypeError: undefined is not a function: checkcreateuser.js:9
checkEmail: checkcreateuser.js:9
onblur: newuser.php:16
to check for the value entered in email and testemail you should use:
var email = document.getElementById("email").value;
var testemail = document.getElementById("testemail").value;// then use split on these values.
if you will use
var email = document.getElementById("email");//you will get error may be like split is not a function or something similar.
Related
i have php page and javascript, the page is contact us form and before submit button there is captcha when form submit it checks captcha if it validate return true else alert and create again captcha but it doesn't work when it return true after that nothing happen
<?php
$action=$_REQUEST['action'];
if ($action=="") /* display the contact form */
{
?>
<form action="" id="demo-form" onsubmit="validateCaptcha()" method="POST" enctype="multipart/form-data" >
<h3>Quick Contact</h3>
<h4>Contact us today, and get reply with in 24 hours!</h4>
<input type="hidden" name="action" value="submit">
<input placeholder="Your name" name="name" id="name" type="text" tabindex="1" required autofocus><br>
<input placeholder="Your Email Address" name="email" id="mail" type="email" tabindex="2" required><br>
<input placeholder="Subject" id="sub" name="subject" type="text" tabindex="3" required><br>
<input placeholder="Mobile Number" name="number" pattern="^((\+92)|(0092)|(0))-{0,1}\d{3}-{0,1}\d{7}$|^\d{11}$|^\d{4}-\d{7}$" id="contactInformation" type="tel" tabindex="4" oninvalid="this.setCustomValidity('Enter mobile number like: 03001234567')"
oninput="this.setCustomValidity('')" > <br>
<textarea placeholder="Type your Message Here...." tabindex="6" name="message" id="msg" tabindex="5" required></textarea><br>
<div id="captcha">
</div><input type="text" placeholder="Enter Captcha Code Here" id="cpatchaTextBox"/><br>
<input name="submit" type="submit" value="Submit" tabindex="7" id="contact-submit" data-submit="...Sending" /><br>
<button type="reset" name="reset" tabindex="8" id="contact-reset">Clear Form</button>
</form>
<?php
}
else /* send the submitted data */
{
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$subject=$_REQUEST['subject'];
$number=$_REQUEST['number'];
$message=$_REQUEST['message'];
if (($name=="")||($email=="")||($subject=="")||($number=="")||($message==""))
{
echo "All fields are required, please fill the form again.";
}
else{
$from="From: $name<$email>\r\nReturn-path: $email";
$msg= "Name: ".$name."\nContact Number: ".$number."\n".$message ;
mail("xyz#gmail.com", $subject, $msg , $from);
echo '<script type="text/javascript">',
'alert("EMAIL SENT..!");',
'setTimeout(function(){',
' window.location.href = "thanks.php";',
' }, 50);',
'</script>'
;
}
}
?>
</div>
</section>
</div>
<br/>
</div>
</div>
</div>
// JavaScript Document
var code;
function createCaptcha() {
//clear the contents of captcha div first
document.getElementById('captcha').innerHTML = "";
var charsArray =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ#!#$%^&*";
var lengthOtp = 6;
var captcha = [];
for (var i = 0; i < lengthOtp; i++) {
//below code will not allow Repetition of Characters
var index = Math.floor(Math.random() * charsArray.length + 1); //get the next character from the array
if (captcha.indexOf(charsArray[index]) == -1)
captcha.push(charsArray[index]);
else i--;
}
var canv = document.createElement("canvas");
canv.id = "captcha";
canv.width = 100;
canv.height = 50;
var ctx = canv.getContext("2d");
ctx.font = "25px Georgia";
ctx.strokeText(captcha.join(""), 0, 30);
//storing captcha so that can validate you can save it somewhere else according to your specific requirements
code = captcha.join("");
document.getElementById("captcha").appendChild(canv); // adds the canvas to the body element
}
function validateCaptcha() {
event.preventDefault();
if (document.getElementById("cpatchaTextBox").value == code) {
return true;
}else{
alert("Invalid Captcha. try Again");
createCaptcha();
}
}
kindly if anyone can do that for me i just want, when captcha validate the form submit and email sent to the person.
There are multiple ways to handle this, one of the simpler solution is to cast event.preventDefault() only when needed.
No need to return anything.
function validateCaptcha() {
if (document.getElementById("cpatchaTextBox").value != code) {
event.preventDefault();
alert("Invalid Captcha. try Again");
createCaptcha();
}
}
WORKING DEMO CAPTCHA OK
function validateCaptcha() {
const captchaMock = false; // switch true/false to see the behavior
if (captchaMock) {
event.preventDefault();
alert("Invalid Captcha. try Again");
createCaptcha();
}
}
function createCaptcha() {
alert('New captcha');
}
<form action="http://www.google.com" onsubmit="validateCaptcha()">
<button>Submit</button>
</form>
WORKING DEMO CAPTCHA NOT OK
function validateCaptcha() {
const captchaMock = true; // switch true/false to see the behavior
if (captchaMock) {
event.preventDefault();
alert("Invalid Captcha. try Again");
createCaptcha();
}
}
function createCaptcha() {
alert('New captcha');
}
<form action="http://www.google.com" onsubmit="validateCaptcha()">
<button>Submit</button>
</form>
onsubmit="validateCaptcha()"
should be
onsubmit="return validateCaptcha()"
to prevent the return value of validateCaptcha being thrown away. In addition, validateCaptcha needs to return boolean false to prevent form submission - returning some other falsey value such as undefined doesn't work.
You can also pass the event object to the validation routine using
onsubmit="return validateCaptcha( event)"
which allows cancelling the event in the validation routine using event methods called on the event argument.
However, adding event handlers in HTML is error-prone, and adding submit event handlers to the form in JavaScript using
formObject.addEventListener("submit", submitHandler, true);
may be preferable - the submit handler gets called with event as its argument.
I wrote a simple script to check my form data upon submission. However it's not supposed to keep sending if the inputs are empty. Why isn't it working?
<script src="scripts/formvalidate.js"></script>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" id="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" id="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" id="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" id="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var result = false;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementById("label").innerHTML = output;
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
result = true;
}
return result;
}
You can't use multiple elements with the same id's since an Id is supposed to identify a uniquely an element of the page (HTML5 Specification says: ID must be document-wide unique.), try to use classes instead, and change your getElementById() to getElementsByClassName() just like this and it should work fine:
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementsByClassName("label").innerHTML = output; //notice how I changed the function used here
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
return true;
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="formvalidate.js"></script>
<title></title>
</head>
<body>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" class="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" class="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" class="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" class="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
</body>
</html>
Note that the asterisk you try to insert, is only inserted in one input for the same reason noted before (multiple ID's are senseless to the DOM). as the DOM tries to fix that, it only get's the first element on the document with the given id (to fix it just change id="asterisk" types to class="asterisk" type).
Plot twist: the reason you probably didn't see any error screen was because (I guess) you were testing it on chrome, which only shows the error for a millisecond. my personal advise is to use firefox for testing purposes, since it won't hide any error at all.
i have tryed to validate textbox using javascript.when i click on the submit button without inserting values to textbox it's display alert box.but after click on "ok" button , page redirect to payments.php page.how to fix it
<form method="post" action="payments.php" >
First Name : <br />
<input name="name" type="text" class="ed" id="name" /> <br />
E-mail : <br />
<input name="email" type="text" class="ed" id="email" /> <br />
<input name="but" type="submit" value="Confirm" onclick="Validation()" />
</form>
function Validation()
{
if (checkFName()&&checkemail())
{
window.event.returnValue = false;
}
}
function checkFName()
{
var tname = document.getElementById("name").value;
if((tname == null)||(tname == ""))
{
alert("Please Enter your First name");
return false;
}
return true;
}
function checkemail()
{
var email = document.getElementById("email").value;
var ap = email.indexOf("#");
var dp = email.lastIndexOf(".");
if((ap < 1)||(dp-ap < 1)||(dp >= email.length-1))
{
alert("invalid email address");
return false;
}
else
return true;
}
You need to change the CONFIRM button type to "button":
<input name="but" type="button" value="Confirm" onclick="Validation()" />
Give your form a name:
<form name="frm" method="post" action="payments.php">
then in your Validation() function, if your form passes validation, you can do the following:
function Validation()
{
if (checkFName()&&checkemail())
{
document.forms["frm"].submit();
}
}
I have a form where username and password are entered. If they are left blank an error is shown, however when one of the input box is filled in and the submit button is clicked the error that's there doesn't go away.
<script type="text/javascript">
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
var user = document.getElementById('username_box').value;
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}else{
valid = true;
}
return valid;
}
</script>
</head>
<body>
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password"> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="button" class="button" id="clear_button" value="Clear">
</div>
</form> <BR>
<center>
<div class="error-area" id="message">
<p id="password-error">
</p>
<p id="user-error">
</p>
</div>
</center>
Only if I fill in both boxes, then the error goes away. I want to hide the error as soon as one of the boxes is filled in with text. Thanks for any help you can give me.
Try using HTML5......just add required attribute and to clear values use reset input
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username" required title="* Please enter username to proceed...">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password" required title="* Please enter password to proceed..."> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="reset" value="Clear">
</div>
</form>
or if you want to achieve this with the existing code try using onfocus event to clear the error message. Hope this hepls
You could run chck() on the "keypress" event for your "username_box" and "password_box" elements.
Like so:
document. getElementById("username_box").addEventListener("keypress", function () {
chck();
}, true);
but update chck slightly to be:
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
document.getElementById('password-error').innerHTML = "";
var user = document.getElementById('username_box').value;
document.getElementById('user-error').innerHTML = "";
document.getElementById('password_box').setAttribute("style", "");
document.getElementById('username_box').setAttribute("style", "");
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}
else{
valid = true;
}
return valid;
}
I'm attempting to move JavaScript event triggers on the two password fields (to alert the user if they're not equal) from within the form elements to
document.getElementById('id_password1').addEventListener('keyUp', checkPass);
document.getElementById('id_password2').addEventListener('keyUp', checkPass);
But the function is never triggered (if I change checkPass to checkPass() the function is called on page-load only, but I don't think this means it's being triggered by the listener). There are no errors in the JavaScript console. If I change the ids to something bogus, it gives this error:
Uncaught TypeError: Cannot read property 'addEventListener' of null
(I'm not familiar enough with the Chrome JavaScript inspector, to know if it can help me further.)
It all works properly if the event triggers are directly in the form elements.
Here are the form elements:
<p>Password: <input id="id_password1" name="password1" type="password" /></p>
<p>Password confirm: <input id="id_password2" name="password2" type="password" /></p>
What am I missing?
<HTML><HEAD>
<TITLE>Create account</TITLE>
</HEAD>
<BODY>
<h1>Create account</h1>
<form id="user_form" method="post" action="/accounts/register/">
<p>Username: <input id="id_username" maxlength="30" name="username" type="text" /> <span class="helptext">Required. 30 characters or fewer. Letters, digits and #/./+/-/_ only.</span></p>
<p>Password: <input id="id_password1" name="password1" type="password" /></p>
<p>Password confirm: <input id="id_password2" name="password2" type="password" /></p>
<span id="confirmMessage" class="confirmMessage"></span>
<input type="submit" name="submit" value="Register" />
</form>
<script language="JavaScript">
function checkPass() {
var pass1 = document.getElementById('id_password1');
var pass2 = document.getElementById('id_password2');
alert("pass1=" + pass1.value + ", pass2=" + pass2.value);
//Check passwords here. Set confirmMessage if bad.
}
document.getElementById('id_password1').addEventListener('keyUp', checkPass);
document.getElementById('id_password2').addEventListener('keyUp', checkPass);
</script>
</BODY></HTML>
The event is case sensitive. Try "keyup" (all lowercase) instead. See this fiddle:
http://jsfiddle.net/LfamexLw/
function checkPass(){
alert("keyup");
}
function checkPass2(){
alert("keyUp");
}
document.getElementById('id_password1').addEventListener('keyup', checkPass);
document.getElementById('id_password1').addEventListener('keyUp', checkPass2);
You'll notice checkPass2 never fires.
Here's the working code, based on #aquinas' answer, including the full check-the-password function:
<HTML><HEAD>
<TITLE>Create account</TITLE>
</HEAD>
<BODY>
<h1>Create account</h1>
<form id="user_form" method="post" action="/accounts/register/"
enctype="multipart/form-data">
<p><label for="id_username">Username:</label> <input id="id_username" maxlength="30" name="username" type="text" /> <span class="helptext">Required. 30 characters or fewer. Letters, digits and #/./+/-/_ only.</span></p>
<p><label for="id_password1">Password:</label> <input id="id_password1" name="password1" type="password" /></p>
<p><label for="id_password2">Password confirmation:</label> <input id="id_password2" name="password2" type="password" /></p>
<!-- Where checkPass() writes its message -->
<span id="confirmMessage" class="confirmMessage"></span>
<P><input type="submit" name="submit" value="Register" /></P>
</form>
<script language="JavaScript">
/*
From (8/27/2014)
http://keithscode.com/tutorials/javascript/3-a-simple-javascript-password-validator.html
Added the "don't print anything if one or both fields are empty" block
*/
function checkPass() {
//Store the password field objects into variables ...
var pass1 = document.getElementById('id_password1');
var pass2 = document.getElementById('id_password2');
//Store the Confimation Message Object ...
var message = document.getElementById('confirmMessage');
//Set the colors we will be using ...
var goodColor = "#66cc66";
var badColor = "#ff6666";
//Compare the values in the password field
//and the confirmation field
if(pass1.value.length === 0 || pass2.value.length === 0) {
pass2.style.backgroundColor = null;
message.style.color = null;
message.innerHTML = "";
return;
}
if(pass1.value === pass2.value){
//The passwords match.
//Set the color to the good color and inform
//the user that they have entered the correct password
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
}else{
//The passwords do not match.
//Set the color to the bad color and
//notify the user.
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
}
}
document.getElementById('id_password1').addEventListener('keyup', checkPass);
document.getElementById('id_password2').addEventListener('keyup', checkPass);
document.getElementById("id_username").focus();
</script>
</BODY></HTML>