I am adding username and email to the userlist and validating email when adding. Validation is working when the page loads for the first time, If I tried to enter invalid email for second time and click the add button it is not working..
<form id="myform">
<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name">
<input id="email" type="text" name="email" placeholder="email">
<button onclick='return addUser();' type="submit">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
<script type="text/javascript">
function addUser(){
var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email');
var entry = document.createElement('li');
if (email.value != '')
{
reg = /^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
if (reg.test(email.value) == true) {
entry.appendChild(document.createTextNode(username + ' ' + email.value));
list.appendChild(entry);
return false;
}
else {
email.className += 'errorclass';
return false;
}
}
else{
alert("Please Enter Email Id");
return false;
}
}
</script>
<style>
.errorclass{
border:1px red solid;
}
</style>
Each time there is a validation error you add 'errorclass' to the email class. So the second time is "errorclasserrorclass" that is not defined in the css.
Use:
email.setAttribute('class','errorclass')
Related
How can I make password field to check each other that the value written by user matches ?
function checkPassword(form) {
pOne = form.pOne.value;
pTwo = form.pTwo.value;
// If password not entered
if (pOne == '')
alert("Please enter Password");
// If confirm password not entered
else if (pTwo == '')
alert("Please enter confirm password");
// If Not same return False.
else if (pOne != pTwo) {
// alert ("\nPassword did not match: Please try again...")
document.querySelector(".submit").addEventListener("click", print)
function print() {
return document.querySelector(".pass").textContent = "Your password does not match!"
}
}
// If same return True.
else {
document.querySelector(".submit").addEventListener("click", print)
function print() {
return document.querySelector(".pass").textContent = "Your password match perfectly!"
}
}
}
<form class="formtwo" onsubmit="checkPassword(this)">
<input type="email" name="email" placeholder="Email"><br>
<input type="password" name="pOne" placeholder="Password">
<input type="password" name="pTwo" placeholder="Re-Type Password">
<p class="pass">djkakj</p>
<button type="submit" class="submit">Submit</button>
</form>
You need to add the event listener to the form submit before you test
window.addEventListener("load", function() {
document.getElementById("formtwo").addEventListener("submit", function(e) {
const pOne = this.pOne.value;
const pTwo = this.pTwo.value;
const pass = document.querySelector(".pass");
let errors = [];
// If password not entered
if (pOne == '') errors.push("Please enter Password");
if (pTwo == '') errors.push("Please enter confirm password");
if (pOne != pTwo) errors.push("Password did not match: Please try again...")
if (errors.length > 0) {
e.preventDefault(); // this will stop submission
alert(errors.join("\n"))
pass.textContent = "Your password does not match!"
return;
}
pass.textContent = "Your password match perfectly!"
})
})
<form id="formtwo">
<input type="email" name="email" placeholder="Email"><br>
<input type="password" name="pOne" placeholder="Password">
<input type="password" name="pTwo" placeholder="Re-Type Password">
<p class="pass">djkakj</p>
<button type="submit" class="submit">Submit</button>
</form>
You can check my solution. Hope it's easier to understand. There were some issues in your code.
If you want to prevent the form submit if the password doesn't match then you need to use event.preventDefault to prevent the default behaviour.
You can fire the submit event once and then check for your required values.
const form = document.querySelector('.formtwo');
form.addEventListener('submit', checkPassword);
function checkPassword(e) {
e.preventDefault();
let pOne = form.pOne.value;
let pTwo = form.pTwo.value;
// If password not entered
if (pOne == "") alert("Please enter Password");
// If confirm password not entered
else if (pTwo == "") alert("Please enter confirm password");
// If Not same return False.
else if (pOne != pTwo) {
document.querySelector(".pass").textContent =
"Your password does not match!";
}
// If same return True.
else {
document.querySelector(".pass").textContent =
"Your password match perfectly!";
// submitting form
form.submit();
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form class="formtwo">
<input type="email" name="email" placeholder="Email"><br>
<input type="password" name="pOne" placeholder="Password">
<input type="password" name="pTwo" placeholder="Re-Type Password">
<p class="pass">Password matching status</p>
<button type="submit" class="submit">Submit</button>
</form>
</body>
</html>
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 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 am validating the email by adding the user and email to the list, the pattern that I provided is not working for some patterns like xyz.xyz kkk.kk and my message is not displaying when it is validating Here is my code..
HTML
<form id="myform">
<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name">
<input id="email" type="text" name="email" placeholder="email">
<button onclick='return addUser();' type="submit">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
JS
function addUser(){
var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email');
var entry = document.createElement('li');
if (email.value != '')
{
reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(email.value) == true) {
entry.appendChild(document.createTextNode(username + ' ' + email.value));
list.appendChild(entry);
return false;
}
else {
email.className += 'errorclass';
email.innerHtml = "Please enter valid emailid";
return false;
}
CSS
.errorclass{
border: 1px red solid;
}
Replace
reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
with
reg = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
Refer JavaScript Regular Expression Email Validation
hey guys i was working on a contact form for my college and i want to validate the contact form but it doesnt seem to be working! can anyone help me on this!
here is my code:
<script type="text/javascript" language="javascript">
function validateMyForm ( ) {
var isValid = true;
var name = document.getElementsByName("Name");
var email = document.getElementsByName("Email");
var phone = document.getElementsByName("Phone");
if ( name == "" ) {
alert ( "Please enter your Name" );
isValid = false;
} else if ( email == "" ) {
alert ( "Please enter your Email ID" );
isValid = false;
} else if ( phone == "" ) {
alert ( "Please enter your Phone Number" );
isValid = false;
}
return isValid;
}
</script>
Body part:
<h3>Contact form:</h3>
<form id="contact-form" method="post">
<fieldset>
<label class="name">
<font color='black'><b><span>Name:</span></b></font><input type="text" id="Name" name="Name"></label>
<label class="email">
<font color='black'><b><span>Email ID:</span></b></font><input type="email" id="Email" name="Email"></label>
<label class="phone"><font color='black'><b><span>Phone:</span></b></font><input type="text" id="Phone" name="Phone"></label>
<label class="message">
<font color='black'><b><span>Queries:</span></b></font><textarea></textarea></label><br><br>
<div class="btns">
<button id="submit" name="submit" onclick="javascript:return validateMyForm();">Send</button>  
<button onClick="document.getElementById('contact-form').reset()">Clear</button>
</div>
</fieldset>
</form>
var name = document.getElementsByName("Name");
That gets a list of elements with name of "name".
var name = document.getElementsByName("Name")[0].value;
That gets the first of the elements with name of "name", then gets the value. You should change all 3 of them.
If you want to have it go by the id, not the name, you can use:
var name = document.getElementById("Name").value;
If you want it to go by name, but not the first in the page, rather the first in the form, use this:
var name = document.getElementById('contact-form').getElementsByName("Name")[0].value;