Javascript validation not working, but PHP validation does - javascript

Case: Php and Javascript validation for Signup Form
So, I am stuck with this problem :
I have a Sign Up page and I validate it using Javascript and PHP.
When I have no PHP validation script, the Javascript validation is working fine. However, after I added PHP validation for the username (to check whether the username exists in the database or no), the javascript validation doesn't work, but the PHP validation works fine.
I include the javascript validation named 'validate.js' in the index file (at head tag)
<script type="text/javascript" src="js/validate.js"></script>
Here is the signup.php file
<?php
//check if there is 'error' in the url (from signup_process.php)
$error = isset($_GET['error']) ? $_GET['error'] : "";
?>
<div class="col s12">
<h3 class="center">Sign Up</h3>
<form action="<?php echo BASE_URL."signup_process.php"; ?>" onsubmit="return validate();" method="POST">
<label class="active" for="email">Email</label>
<input type="text" id="email" name="email" class="validate">
<div class="error" id="erremail"></div>
<label class="active" for="username">Username</label>
<input type="text" name="username" id="username">
<div class="error" id="errusername"></div>
<?php if($error=="username") echo "<div class='error'>Username already exists</div>"; //if error exists (from signup_process.php) ?>
<label class="active" for="password">Password</label>
<input type="password" name="password" id="password">
<div class="error" id="errpass"></div>
<label class="active" for="re-password">Retype Password</label>
<input type="password" name="re-password" id="re-password">
<div class="error" id="errrepass"></div>
<div class="center">
<button class="btn waves-effect waves-light blue lighten-2" type="submit" name="submit">Sign Up
<i class="material-icons right">send</i>
</button>
</div>
</form>
</div>
After the user entered all the data and validated by javascript, then the data will go to 'signup_process.php', here's the code
<?php
include_once("function/helper.php");
include_once("function/connect.php");
$email = mysqli_real_escape_string($conn, $_POST['email']);
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, md5($_POST['password']));
//check if username exists
$cekUsername = mysqli_query($conn, "SELECT * FROM user WHERE username = '$username'");
//unset password so it doesn't show up in the url if the username exists
unset($_POST['password']);
//show email and username in url if username exists
$data = http_build_query($_POST);
if(mysqli_num_rows($cekUsername) == 1){ //if username exists, show the form data in the url to get validated by php at signup.php
header("location: ".BASE_URL."index.php?page=signup&error=username&$data");
}else{ //signup success
mysqli_query($conn, "INSERT INTO user (username, password, email, display_name) VALUES ('$username', '$password', '$email', '$username')");
//Set code for email verif
$code = rand(3010, 9753);
//Parameter for email verif
$to = $email;
$subject = "Email Verification Code for Daforums";
$message = "Your activation code is " . $code ;
$header = "from : no-reply#daforums.xyz";
mail('lionel.ritchie#yahoo.com',$subject,$message,$header);
header("location: ".BASE_URL."index.php?page=login");
}
?>
The javascript validation script 'validate.js' :
function validate(){
let result = true;
let username = document.getElementById('username').value;
let errusername = document.getElementById('errusername');
let email = document.getElementById('email').value;
let erremail = document.getElementById('erremail');
let password = document.getElementById('password').value;
let errpass = document.getElementById('errpass');
let repassword = document.getElementById('re-password').value;
let errrepass = document.getElementById('errrepass');
const emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
const usernameRegex = /^[a-zA-Z0-9_]*$/;
//Email
if(email == ""){
erremail.innerHTML = "Email can't be empty";
result = false;
else if(!emailRegex.test(email)) {
erremail.innerHTML = "Invalid e-mail format";
result = false;
}else{
erremail.innerHTML = "";
}
// Username
if(username == ""){
errusername.innerHTML = "Username can't be empty";
result = false;
}else if(!usernameRegex.test(username)) {
errusername.innerHTML = "Username must only contain alphanumeric characters";
result = false;
}else if(username.length < 6 || username.length > 20) {
errusername.innerHTML = "Username must be between 6 and 20 characters long";
result = false;
}else{
errusername.innerHTML = "";
}
//Password
if(password==""){
errpass.innerHTML = "Password can't be empty";
result = false;
}else if (password.length < 8){
errpass.innerHTML = "Password must be at least 8 characters long";
result = false;
}else if (password != repassword){
errrepass.innerHTML = "Please correctly confirm the password";
result = false;
}else{
errpass.innerHTML = "";
errrepass.innerHTML = "";
}
return result;
}
Before the php validation in signup.php was added, the javascript validation works fine.
(So if if remove the code below, the javascript validation will work).
the php validation is located in signup.php pages above, here is the code:
<?php
//check if there is 'error' in the url (from signup_process.php)
$error = isset($_GET['error']) ? $_GET['error'] : "";
?>
<?php if($error=="username") echo "<div class='error'>Username already exists</div>"; //if error exists (from signup_process.php) ?>
I've been searching for this problem but nothing matched my problems. Any help will be appreciated ^^, Thank you.

hey its have nothing between php query parameter and js validation
but i have find one thing in your js code
//Email
if(email == ""){
erremail.innerHTML = "Email can't be empty";
result = false;
else if(!emailRegex.test(email)) {
erremail.innerHTML = "Invalid e-mail format";
result = false;
}else{
erremail.innerHTML = "";
}
in this portion of your validation you forgot to add closing brackets of if condition
add closing bracket and check code like this
//Email
if(email == ""){
erremail.innerHTML = "Email can't be empty";
result = false;
}else if(!emailRegex.test(email)) {
erremail.innerHTML = "Invalid e-mail format";
result = false;
}else{
erremail.innerHTML = "";
}

#bharat savani and #ChandraShekar were right about javascript
it just was close if bracket in email validation
Run this snippet I works Ok
You really can be problems with your enviroments if you dont get the changes
so you mark [wrong] two good answer, be careful next time.
function validate() {
let result = true;
let username = document.getElementById('username').value;
let errusername = document.getElementById('errusername');
let email = document.getElementById('email').value;
let erremail = document.getElementById('erremail');
let password = document.getElementById('password').value;
let errpass = document.getElementById('errpass');
let repassword = document.getElementById('re-password').value;
let errrepass = document.getElementById('errrepass');
const emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
const usernameRegex = /^[a-zA-Z0-9_]*$/;
//Email
if (email == "") {
erremail.innerHTML = "Email can't be empty";
result = false;
} else if (!emailRegex.test(email)) {
erremail.innerHTML = "Invalid e-mail format";
result = false;
} else {
erremail.innerHTML = "";
}
// Username
if (username == "") {
errusername.innerHTML = "Username can't be empty";
result = false;
} else if (!usernameRegex.test(username)) {
errusername.innerHTML = "Username must only contain alphanumeric characters";
result = false;
} else if (username.length < 6 || username.length > 20) {
errusername.innerHTML = "Username must be between 6 and 20 characters long";
result = false;
} else {
errusername.innerHTML = "";
}
//Password
if (password == "") {
errpass.innerHTML = "Password can't be empty";
result = false;
} else if (password.length < 8) {
errpass.innerHTML = "Password must be at least 8 characters long";
result = false;
} else if (password != repassword) {
errrepass.innerHTML = "Please correctly confirm the password";
result = false;
} else {
errpass.innerHTML = "";
errrepass.innerHTML = "";
}
return result;
}
<!doctype html>
<html lang="en"><head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="col s12">
<h3 class="center">Sign Up</h3>
<form action="/action_page.php" onsubmit="return validate()"
method="POST">
<label class="active" for="email">Email</label>
<input type="text" id="email" name="email" class="validate">
<div class="error" id="erremail"></div>
<label class="active" for="username">Username</label>
<input type="text" name="username" id="username">
<div class="error" id="errusername"></div>
<label class="active" for="password">Password</label>
<input type="password" name="password" id="password">
<div class="error" id="errpass"></div>
<label class="active" for="re-password">Retype Password</label>
<input type="password" name="re-password" id="re-password">
<div class="error" id="errrepass"></div>
<div class="center">
<button class="btn waves-effect waves-light blue lighten-2 btn btn-primary" type="submit" name="submit">Sign Up
<i class="material-icons right">send</i>
</button>
</div>
</form>
</div>
<script>
function validate() {
let result = true;
let username = document.getElementById('username').value;
let errusername = document.getElementById('errusername');
let email = document.getElementById('email').value;
let erremail = document.getElementById('erremail');
let password = document.getElementById('password').value;
let errpass = document.getElementById('errpass');
let repassword = document.getElementById('re-password').value;
let errrepass = document.getElementById('errrepass');
const emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
const usernameRegex = /^[a-zA-Z0-9_]*$/;
//Email
if (email == "") {
erremail.innerHTML = "Email can't be empty";
result = false;
} else if (!emailRegex.test(email)) {
erremail.innerHTML = "Invalid e-mail format";
result = false;
} else {
erremail.innerHTML = "";
}
// Username
if (username == "") {
errusername.innerHTML = "Username can't be empty";
result = false;
} else if (!usernameRegex.test(username)) {
errusername.innerHTML = "Username must only contain alphanumeric characters";
result = false;
} else if (username.length < 6 || username.length > 20) {
errusername.innerHTML = "Username must be between 6 and 20 characters long";
result = false;
} else {
errusername.innerHTML = "";
}
//Password
if (password == "") {
errpass.innerHTML = "Password can't be empty";
result = false;
} else if (password.length < 8) {
errpass.innerHTML = "Password must be at least 8 characters long";
result = false;
} else if (password != repassword) {
errrepass.innerHTML = "Please correctly confirm the password";
result = false;
} else {
errpass.innerHTML = "";
errrepass.innerHTML = "";
}
return result;
}
</script>
</body>
</html>

Hi your code has one issue, you have missed the closing bracket(}) in your js code at email validation line(59).
function validate(){
let result = true;
let username = document.getElementById('username').value;
let errusername = document.getElementById('errusername');
let email = document.getElementById('email').value;
let erremail = document.getElementById('erremail');
let password = document.getElementById('password').value;
let errpass = document.getElementById('errpass');
let repassword = document.getElementById('re-password').value;
let errrepass = document.getElementById('errrepass');
const emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
const usernameRegex = /^[a-zA-Z0-9_]*$/;
//Email
if(email == ""){
erremail.innerHTML = "Email can't be empty";
result = false;
}//(59 you have missed this)
else if(!emailRegex.test(email)) {
erremail.innerHTML = "Invalid e-mail format";
result = false;
}else{
erremail.innerHTML = "";
}
// Username
if(username == ""){
errusername.innerHTML = "Username can't be empty";
result = false;
}else if(!usernameRegex.test(username)) {
errusername.innerHTML = "Username must only contain alphanumeric characters";
result = false;
}else if(username.length < 6 || username.length > 20) {
errusername.innerHTML = "Username must be between 6 and 20 characters long";
result = false;
}else{
errusername.innerHTML = "";
}
//Password
if(password==""){
errpass.innerHTML = "Password can't be empty";
result = false;
}else if (password.length < 8){
errpass.innerHTML = "Password must be at least 8 characters long";
result = false;
}else if (password != repassword){
errrepass.innerHTML = "Please correctly confirm the password";
result = false;
}else{
errpass.innerHTML = "";
errrepass.innerHTML = "";
}
return result;
}
Now you can use above code, and it will works.

Related

Clearing validation errors JavaScript

I have been attempting to clear messages once the user has successfully input completed the required validation rules, however I can't seem to clear all the validation errors, I did look around and tried what was suggested however it doesn't seem to have worked. I thought by placing empty innerHTML strings might work as I said it had been suggested within other posts
<form action ="" method="POST">
<span id="tryErr"></span><br>
<input type="text" id="username" placeholder="Username"><br>
<span id="usernameErr"></span><br>
<input type="text" id="email" placeholder="Email address"><br>
<span id="emailErr"></span><br>
<input type="password" id="password" placeholder="Password"><br>
<span id="passwordErr"></span><br>
<input type="submit" value="Submit" onclick=" return confirmValidation();">
</form>
JS
<script type="text/javascript">
function validateUsername(username, error){
var username = document.getElementById("username").value,
error = document.getElementById("usernameErr");
if(username == null || username==""){
return error.innerHTML = "Username is required";
return false;
}
else if(!username.match(/^[0-9a-z]+$/) || username.length < 3){
return error.innerHTML = "Username must be alphanumeric and three characters long";
return false;
}
else{
return error.innerHTML = "";
return true;
}
}
function validatePassword(password, error){
var password = document.getElementById("password").value,
error = document.getElementById("passwordErr");
if(password == null || password==""){
return error.innerHTML = "Password is required";
return false;
}
else if(password.length < 7){
return error.innerHTML = "Password must be seven characters long";
return false;
}
else{
return error.innerHTML = "";
return true;
}
}
function validateEmail(email, error){
var email = document.getElementById("email").value,
apos = email.indexOf("#"),
dotpos = email.lastIndexOf("."),
error = document.getElementById("emailErr");
if(email == null || email==""){
return error.innerHTML = "Email is required";
return false;
}
if (apos < 1 || dotpos-apos < 2 || dotpos == (email.length - 1)){
return error.innerHTML = "Please enter a valid email";
return false;
}
else{
return error.innerHTML = "";
return true;
}
}
function confirmValidation(e){
event.preventDefault(e);
if(!validateUsername()){
return false;
}
if(!validatePassword()){
return false;
}
if(!validateEmail()){
return false;
}
else{
//do something clever here
}
}
</script>
You should use onchange event on input types .
Like
<input type="text" id="username" placeholder="Username " onchange="validateUsername()">

Retrieving ajax data synchronously back to calling function

I have a form featuring the google captcha code: http://code.google.com/p/cool-php-captcha.
As this captcha uses a session to store the captcha I am having difficulty retrieving the upto date variable of the session into javascript through ajax. It was working well when my ajax command was using the async: false flag but as this is being depreciated I would rather not use it.
My problem at the moment is that I am trying to use a callback function to retrieve the value but by trying to send the value back to the original function I am creating a loop between my 2 functions and can't quite figure out the best way to get what I want.
thanks for any help cheers Callum
<script type="text/javascript">
function getcaptchsession()
{
$.ajax({url:'/Includes/Session.php', cache:false, type: 'GET', success:function(data, status, XHR){validate(data);}});
}
function validate(data)
{
var session = data;
var ok = '';
var nameerror = '';
var emailerror = '';
var subjecterror = '';
var messageerror = '';
var contactform = document.forms.ContactForm;
var fullname = contactform.Fullname.value;
var emailadd = contactform.Emailadd.value;
var subject = contactform.Subject.value;
var message = contactform.Message.value;
var captcha = contactform.CaptchaText.value;
getcaptchsession();
if (fullname == "")
{
var x = document.getElementsByClassName("error");
x[0].innerHTML = "Name field is a required field.";
nameerror = true;
}
else if (fullname != "")
{
if (/[^a-z\s-]/i.test(fullname))
{
var x = document.getElementsByClassName("error");
x[0].innerHTML = "Alphabetic characters only.";
nameerror = true;
}
else
{
var x = document.getElementsByClassName("error");
x[0].innerHTML = "";
nameerror = false;
}
}
if (emailadd == "")
{
var x = document.getElementsByClassName("error");
x[1].innerHTML = "Email field is a required field.";
emailerror = true;
}
else if (emailadd != "")
{
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailadd))
{
var x = document.getElementsByClassName("error");
x[1].innerHTML = "";
emailerror = false;
}
else
{
var x = document.getElementsByClassName("error");
x[1].innerHTML = "Email is not a valid email address.";
nameerror = true;
}
}
if (subject == "")
{
var x = document.getElementsByClassName("error");
x[2].innerHTML = "Subject field is a required field.";
subjecterror = true;
}
else
{
var x = document.getElementsByClassName("error");
x[2].innerHTML = "";
subjecterror = false;
}
if (message == "")
{
var x = document.getElementsByClassName("error");
x[3].innerHTML = "Message field is a required field.";
messageerror = true;
}
else
{
var x = document.getElementsByClassName("error");
x[3].innerHTML = "";
messageerror = false;
}
if (captcha == "")
{
var x = document.getElementsByClassName("error");
x[4].innerHTML = "The captcha field is a required field.";
messageerror = true;
}
else if (captcha != "")
{
if (captcha != session)
{
var x = document.getElementsByClassName("error");
x[4].innerHTML = "Captcha mismatch.";
messageerror = true;
}
else
{
var x = document.getElementsByClassName("error");
x[4].innerHTML = "";
messageerror = false;
}
}
if (nameerror == true || emailerror == true || subjecterror == true || messageerror == true || captcha == true)
{
return false;
}
else
{
return true;
}
}
</script>
My form is as follows:
<form id="ContactForm" name="ContactForm" action="javascript:loadDoc();" onsubmit="return(validate());">
<label for="Fullname">Name <span class="red">*</span><span class="error"></span></label>
<input id="ContactFormInput" name="Fullname" class="text" id="Fullname">
<label for="Emailadd">Email <span class="red">*</span><span class="error"></span></label>
<input id="ContactFormInput" name="Emailadd" class="text" id="Emailadd">
<label for="Subject">Subject <span class="red">*</span><span class="error"></span></label>
<input id="ContactFormInput" name="Subject" class="text" id="Subject">
<label for="Message">Message <span class="red">*</span><span class="error"> </span></label>
<textarea id="Message" name="Message" rows="6" cols="30"></textarea>
<label for="CaptchaText" id="captchalabel">Captcha <span class="red">*</span><span class="error"></span></label>
<div id="CaptchaParent">
<div id="CaptchaIframe">
<img src="/Includes/captcha.php" id="captcha" />
</div><div id="CaptchaReload">
<img class="captchareload" src="/Images/Contact_Us/reload_icon.png" onclick="document.getElementById('captcha').src='/Includes/captcha.php?'+Math.random()">
</div><div id="CaptchaInput">
<input name="CaptchaText" id="CaptchaText" maxlength="8" class="text">
</div>
</div>
<div id="ContactInput">
<input id="Submit" class="ContactButton" type="submit" name="submit" class="button" value="Send Now"/>
</div>
</form>
My php session page has
<?php
session_start();
echo $_SESSION['captcha'];
?>

Javascript Form Validation Not Successful

Practicing my Javascript on a simple HTML form. Enter password in one box, enter again to confirm in the second. Password should contain 6 character (including 1 number), and no spaces. An alert message should pop up if the passwords meet the criteria and match.
I have it mostly there, in that the error messages pop up if the criteria aren't met, but I can't get to alert "Success!" I've toyed with the if statements so many ways, I'm not sure what I'm missing. Any suggestions?
Javascript:
window.onload = function() {
document.getElementById('submit').addEventListener('click', validateInput);
}
var userPass = document.getElementById('password').value;
var confirmPass = document.getElementById('confirm_password').value;
function validatePassword() {
var userPass = document.getElementById('password').value;
if (userPass.length == 0) { // Nothing was entered
document.getElementById('password_error').innerHTML = 'Please enter a password';
} else if (userPass.length < 6) { // Less than 6 chars
document.getElementById('password_error').innerHTML = 'Your password must be at least 6 characters in length';
} else if (userPass.match(/\s/)) { // contains a space
document.getElementById('password_error').innerHTML = 'Your password cannot contain spaces';
} else if (!userPass.match(/\d/)) { // Does not contain a number
document.getElementById('password_error').innerHTML = 'Your password must contain a number';
} else if (userPass !== confirmPass) {
document.getElementById('confirm_error').innerHTML = 'Passwords do not match. Please check again.';
} else {
document.getElementById('password_error').innerHTML = "";
document.getElementById('confirm_error').innerHTML = "";
alert("Success!");
clearFields();
}
}
function validateConfirm() {
function clearFields (){
document.getElementById('password').value=null;
document.getElementById('confirm_password').value=null;
}
if (confirmPass.length == 0) {
document.getElementById('confirm_error').innerHTML = "Please confirm password to proceed";
} else if (confirmPass.length < 6) {
document.getElementById('confirm_error').innerHTML = "Your password must be at least 6 characters in length";
} else if (userPass !== confirmPass) {
document.getElementById('confirm_error').innerHTML = 'Passwords do not match. Please check again.';
} else {
document.getElementById('password_error').innerHTML = "";
document.getElementById('confirm_error').innerHTML = "";
alert("Success!");
clearFields();
}
}
function validateInput() {
validatePassword();
validateConfirm();
}
The form:
<form>
<fieldset>
<legend>CONFIRM PASSWORD</legend>
<label for="name">Password: </label>
<input type="text" id="password" size="10" />
<p id="password_error" class="error"></p>
<label for="name">Confirm Password: </label>
<input type="text" id="confirm_password" size="10" />
<p id="confirm_error" class="error"></p>
<button id="submit">Submit</button>
</fieldset>
</form>
I've found two fault in your code
Set clearFields() function outside function validatePassword();
var confirmPass enter inside function or pass from calling function
window.onload = function () {
document.getElementById('submit').addEventListener('click', validateInput);
}
function validatePassword() {
var userPass = document.getElementById('password').value;
var confirmPass = document.getElementById('confirm_password').value;
if (userPass.length == 0) { // Nothing was entered
document.getElementById('password_error').innerHTML = 'Please enter a password';
} else if (userPass.length < 6) { // Less than 6 chars
document.getElementById('password_error').innerHTML = 'Your password must be at least 6 characters in length';
} else if (userPass.match(/\s/)) { // contains a space
document.getElementById('password_error').innerHTML = 'Your password cannot contain spaces';
} else if (!userPass.match(/\d/)) { // Does not contain a number
document.getElementById('password_error').innerHTML = 'Your password must contain a number';
} else if (userPass !== confirmPass) {
document.getElementById('confirm_error').innerHTML = 'Passwords do not match. Please check again.';
} else {
document.getElementById('password_error').innerHTML = "";
document.getElementById('confirm_error').innerHTML = "";
alert("Success!");
clearFields();
}
}
function clearFields() {
document.getElementById('password').value = null;
document.getElementById('confirm_password').value = null;
}
function validateConfirm() {
var userPass = document.getElementById('password').value;
var confirmPass = document.getElementById('confirm_password').value;
if (confirmPass.length == 0) {
document.getElementById('confirm_error').innerHTML = "Please confirm password to proceed";
} else if (confirmPass.length < 6) {
document.getElementById('confirm_error').innerHTML = "Your password must be at least 6 characters in length";
} else if (userPass !== confirmPass) {
document.getElementById('confirm_error').innerHTML = 'Passwords do not match. Please check again.';
} else {
document.getElementById('password_error').innerHTML = "";
document.getElementById('confirm_error').innerHTML = "";
alert("Success!");
clearFields();
}
}
function validateInput() {
validatePassword();
validateConfirm();
}
<form>
<fieldset>
<legend>CONFIRM PASSWORD</legend>
<label for="name">Password: </label>
<input type="text" id="password" size="10" />
<p id="password_error" class="error"></p>
<label for="name">Confirm Password: </label>
<input type="text" id="confirm_password" size="10" />
<p id="confirm_error" class="error"></p>
<button id="submit">Submit</button>
</fieldset>
</form>
There are multiple issues
The function clearFields() is available only inside validateConfirm
You are reading the value of the confirm input only once at the page load, you need to read the new value within the validate method else it will always be empty string
Since you are validating the policy in the password field, not need to check it again for the confirm field since you are checking whether the confirm and password fields are the same
window.onload = function() {
document.getElementById('submit').addEventListener('click', validateInput);
}
function validatePassword() {
var userPass = document.getElementById('password').value;
var confirmPass = document.getElementById('confirm_password').value;
if (userPass.length == 0) { // Nothing was entered
document.getElementById('password_error').innerHTML = 'Please enter a password';
} else if (userPass.length < 6) { // Less than 6 chars
document.getElementById('password_error').innerHTML = 'Your password must be at least 6 characters in length';
} else if (userPass.match(/\s/)) { // contains a space
document.getElementById('password_error').innerHTML = 'Your password cannot contain spaces';
} else if (!userPass.match(/\d/)) { // Does not contain a number
document.getElementById('password_error').innerHTML = 'Your password must contain a number';
} else if (userPass !== confirmPass) {
document.getElementById('password_error').innerHTML = "";
document.getElementById('confirm_error').innerHTML = 'Passwords do not match. Please check again.';
} else {
document.getElementById('password_error').innerHTML = "";
document.getElementById('confirm_error').innerHTML = "";
alert("Success!");
clearFields();
return true;
}
return false;
}
function clearFields() {
document.getElementById('password').value = '';
document.getElementById('confirm_password').value = '';
}
function validateInput() {
return validatePassword();
}
<fieldset>
<legend>CONFIRM PASSWORD</legend>
<label for="name">Password:</label>
<input type="text" id="password" size="10" />
<p id="password_error" class="error"></p>
<label for="name">Confirm Password:</label>
<input type="text" id="confirm_password" size="10" />
<p id="confirm_error" class="error"></p>
<button id="submit">Submit</button>
</fieldset>

validation is not done on submit button click

<script>
function ValidateEmail(){
var emailID = document.getElementById("email").value;
var email = document.getElementById("email");
var emailRegexp=/^[a-z]+\w+([\.-]?\w+)*#[a-z]+\w+([\.-]?\w+)*(\.[a-z]{2,3})+$/i;
if ((emailID==null)||(emailID=="")){
// alert("Please Enter your Email ID");
email.style.borderColor="red";
document.getElementById("err").innerHTML = "Please Enter your Email ID";
emailID.focus();
return false;
}
else
if (!emailRegexp.test(emailID)){
//alert("Please Enter valid Email ID");
email.style.borderColor="red";
document.getElementById("err").innerHTML = "Please Enter valid Email ID";
emailID.focus();
return false;
}
else
{
email.style.borderColor="#e1e1e1";
document.getElementById("err").innerHTML ="";
return true;
}
}
function validUsername()
{
var error = "";
var illegalChars = /\W/; // No special Characters allowed
var fd =document.getElementById("name");
if (fd.value == "" || fd.value == null)
{
fd.style.borderColor = 'Red';
document.getElementById("UserErr").innerHTML = " Field is left Blank.\n";
return false;
}
else if ((fd.value.length < 5) || (fd.value.length > 20)) // Number of Character entered is checked
{
fd.style.borderColor = 'Red';
document.getElementById("UserErr").innerHTML = "Username is should be in a range of 5 and 15..\n";
return false;
}
else if (illegalChars.test(fd.value)) // check for illegal characters
{
fd.style.borderColor = 'Red';
document.getElementById("UserErr").innerHTML = "Illegal Characters not allowed\n";
return false;
}
else
{
fd.style.borderColor = '#e1e1e1';
document.getElementById("UserErr").innerHTML = "";
return true;
}
}
function validPassword()
{
var error = "";
var password=document.getElementById("pass");
var passError=document.getElementById("PassErr");
var illegalChars = /[\W_]/; // Numbers and letter only
var checkPass=/\w*[a-z]+\d+\w*/i;
if (password.value == "" || password.value == null)
{
password.style.borderColor = 'Red';
passError.innerHTML = "Field Cannot be blank.\n";
return false;
}
else if ((password.value.length < 8) || (password.value.length > 20)) // Checks length of the password
{
password.style.borderColor = 'Red';
passError.innerHTML = "Length should be in Range of 8 to 20. \n";
return false;
}
else if (illegalChars.test(password.value))
{
password.style.borderColor = 'Red';
passError.innerHTML = "Illegal characters not allowed.\n";
return false;
}
else if (!checkPass.test(password.value)) // Checks for numeric value in entered password
{
password.style.borderColor = 'Red';
passError.innerHTML = "Atleast one Numeric value Required ";
return false;
}
else
{
password.style.borderColor = '#e1e1e1';
passError.innerHTML = "";
return true;
}
}
function validateOnSubmit()
{
if(ValidateEmail() && validUsername() && validPassword());
return true;
return false;
}
</script>
<form method="post" name="form">
<!--<input type="text" name="email" id="email" placeholder="Your Email" onblur="return ValidateEmail()"/><span id="err"></span></td>-->
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="uname" id="name" placeholder="User Name" onblur="validUsername()"/><span id="UserErr" style="color:red"></span></td>
</tr>
<tr>
<td><input type="text" name="email" id="email" placeholder="Your Email" onblur="ValidateEmail()"/><span id="err"></span></td>
</tr>
<tr>
<td><input type="password" name="pass" id="pass" placeholder="Your Password" onblur="validPassword()" /><span id="PassErr" style="color:red"></span></td>
</tr>
<tr>
<td><button type="submit" onsubmit="return validateOnSubmit()" name="btn-signup">Sign Me Up</button></td>
</tr>
</table>
</form>
I have created registration form and create validation in JavaScript for input fields.
onBlur validation is done, and works fine.
But when I click on the 'Sign Me Up' button, validation is not done and data is inserted into the database. Please I need help.
submit events fire on forms, not submit buttons. Move the onsubmit attribute to the <form> start tag.
"emailID.focus(); " is wrong is in ValidateEmail() function. instead of it
"email.focus(); is right.
Now it works fine as i expected.
but there is no need of this so i removed it.

Can't hide innerHTML after error corrected

Didn't see an answer so here goes. Error messages are using innerHTML. How do I get them to disappear once the error is corrected? Right now it just stays on. I tried resetting at the top of the script.
JSfiddle
HTML:
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="" method="post">
<h2>Contact Me</h2>
<div id="main-error"></div>
<div>
<label>Name</label>
<input placeholder="First Name" type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error"></div>
</div>
<div>
<label>Email</label>
<input placeholder="Email" type="email" name="email" id="email" tabindex="3" autofocus />
<div id="email-error"></div>
</div>
<div>
<label>Phone</label>
<input placeholder="Phone" type="text" name="phone" id="phone" tabindex="4" autofocus />
<div id="test"></div>
</div>
<div>
<button type="submit" name="submit" id="submit" tabindex="5">Send</button>
</div>
</form>
JS:
document.getElementById('name-error').innerHTML='';
document.getElementById('email-error').innerHTML='';
document.getElementById('phone-error').innerHTML='';
function validateFormOnSubmit(contact) {
var reason = "";
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validateEmpty(contact.name);
if (reason != "") {
document.getElementById("main-error").innerHTML="Test main error message area";
return false;
}
return false;
}
// validate required fields
function validateEmpty(name) {
var error = "";
if (name.value.length == 0) {
name.style.background = 'Yellow';
document.getElementById('name-error').innerHTML="The required field has not been filled in";
} else {
name.style.background = 'White';
}
return error;
}
// validate email as required field and format
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error="";
var temail = trim(email.value); // value of field with whitespace trimmed off
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (email.value == "") {
email.style.background = 'Yellow';
document.getElementById('email-error').innerHTML="Please enter an email address.";
} else if (!emailFilter.test(temail)) { //test email for illegal characters
email.style.background = 'Yellow';
document.getElementById('email-error').innerHTML="Please enter a valid email address.";
} else if (email.value.match(illegalChars)) {
email.style.background = 'Yellow';
document.getElementById('email-error').innerHTML="Email contains invalid characters.";
} else {
email.style.background = 'White';
}
return error;
}
// validate phone for required and format
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('test').innerHTML="Please enter a phone number";
phone.style.background = 'Yellow';
} else if (isNaN(parseInt(stripped))) {
document.getElementById('test').innerHTML="The phone number contains illegal characters.";
phone.style.background = 'Yellow';
} else if (!(stripped.length == 10)) {
document.getElementById('test').innerHTML="The phone number is too short.";
phone.style.background = 'Yellow';
}
return error;
}
thanks!
function validateFormOnSubmit(contact) {
reason = "";
reason += validateEmpty(contact.name);
reason+= validateEmail(contact.email);
reason+= validatePhone(contact.phone);
console.log(reason);
if ( reason.length>0 ) {
return false;
}
else {
return true;
}
}
// validate required fields
function validateEmpty(name) {
var error = "";
if (name.value.length == 0) {
name.style.background = 'Yellow';
document.getElementById('name-error').innerHTML="The required field has not been filled in";
var error = "1";
} else {
name.style.background = 'White';
document.getElementById('name-error').innerHTML='';
}
return error;
}
// validate email as required field and format
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error="";
var temail = trim(email.value); // value of field with whitespace trimmed off
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (email.value == "") {
email.style.background = 'Yellow';
document.getElementById('email-error').innerHTML="Please enter an email address.";
var error="2";
} else if (!emailFilter.test(temail)) { //test email for illegal characters
email.style.background = 'Yellow';
document.getElementById('email-error').innerHTML="Please enter a valid email address.";
var error="3";
} else if (email.value.match(illegalChars)) {
email.style.background = 'Yellow';
var error="4";
document.getElementById('email-error').innerHTML="Email contains invalid characters.";
} else {
email.style.background = 'White';
document.getElementById('email-error').innerHTML='';
}
return error;
}
// validate phone for required and format
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('test').innerHTML="Please enter a phone number";
phone.style.background = 'Yellow';
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error="5";
document.getElementById('test').innerHTML="The phone number contains illegal characters.";
phone.style.background = 'Yellow';
} else if (stripped.length < 10) {
var error="6";
document.getElementById('test').innerHTML="The phone number is too short.";
phone.style.background = 'Yellow';
}
else {
phone.style.background = 'White';
document.getElementById('test').innerHTML='';
}
return error;
}
http://jsfiddle.net/tX5y5/59/
I have just changed place of inner html cleaning... and i have added some changes in whole validation (it didn't worked before properly).
You'll need to register a listener for when the user changes one of your input fields and run your validation function in the listener. Something like this:
document.getElementById('name').addEventListener("change", validateFormOnSubmit);
document.getElementById('email').addEventListener("change", validateFormOnSubmit);
document.getElementById('phone').addEventListener("change", validateFormOnSubmit);
If at all possible I'd recommend using an existing library for form validation (but you probably already knew that).

Categories

Resources