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>
Related
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.
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()">
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Help, I am trying to validate my form. It can validate all fields, but not submitting after validated. I tried to run the codes in http://jsfiddle.net/CrLsR/297/ but after validated the form, it can't proceed to the test.html page. I'm new in javascript so, I can't figure out what is the probleml. Any help will very much appreciated. thanks..
here is the code :
//HTML FORM
<form name="form" id="form" onsubmit="return (validateForm(this));" action="test.htm" method="post">
<label for="firstname" id="errfName">First Name</label>
<li><input name="firstname" type="text" onkeyup="return(validatefName(this));"> <span id="warnfName"></span></li>
<label for="username" id="errUser">Username</label>
<li><input name="username" type="text" onkeyup="return(validateUsername(this));"> <span id="warnUser"></span></li>
<label for="password" id="errPass">Password</label></li>
<li><input name="password" id="password" type="password" onkeyup="return(validatePassword(this));"> <span id="warnPass"></span></li>
<label for="password2" id="errPass2">Confirm Password</label></li>
<li><input name="password2" id="password2" type="password" onkeyup="return(validatePassword2(this));"> <span id="warnPass2"></span></li>
<label for="email" id="errEmail">Email Address</label>
<li><input name="email" type="text" onkeyup="return(validateEmail(this));"> <span id="warnEmail"></span></li>
<li> </td>
<li><input name="Submit" value="Send" type="submit" ></li>
// Javascript code
var borderErr = "1px solid rgb(100,0,50)";
var borderOk = "1px solid rgb(0,150,50)";
var warn = "<b class='warn'>!</b>";
// for First Name validation
var matchfName = /^[a-zA-Z]$/;
var errorfNameEmpty = "<b class='err'>First name is required";
// for Username validation
var matchUsername = /^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$/;
var matchUsername2 = /^[a-z0-9_-]{5,15}$/;
var errorUsernameEmpty = "<b class='err'>Username is required\n</b>";
var errorUsernameInvalid = "<b class='err'>The username is not valid. Must contains 5 to 15 alpha numeric characters\n</b>";
// for Password validation
var matchPass = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{7,15}$/;
var errPassEmpty = "<b class='err'>Password is required</b>";
var errPassInvalid = "<b class='err'>Password must contains with a combination of <br/>7 to 15 alpha numeric and special characters.";
// for Confirm Password validation
var errPassEmpty2 = "<b class='err'>Confirm password is required</b>";
var errPassInvalid2 = "<b class='err'>Confirm password must the same as password value.";
// for Email validation
var matchEmail = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var errEmailEmpty = "<b class='err'>Email address is required</b>";
var errEmailInvalid = "<b class='err'>Invalid email address. Please enter a valid email.";
function validateForm(regForm) {
var warning = "";
warning += validatefName(regForm.firstname);
warning += validateUsername(regForm.username);
warning += validatePassword(regForm.password);
warning += validatePassword2(regForm.password2);
warning += validateEmail(regForm.email);
if (warning != "") {
return false;
}
return true;
}
// validate first name
function validatefName(fld) {
if(fld.value == "") {
fld.style.border=borderErr;
document.getElementById("errfName").innerHTML=errorfNameEmpty;
document.getElementById("warnfName").innerHTML=warn;
return false;
}
else {
fld.style.border=borderOk;
document.getElementById("errfName").innerHTML="First Name";
document.getElementById("warnfName").innerHTML="";
return true;
}
}
//validate username
function validateUsername(fld) {
if (fld.value == "") {
fld.style.border=borderErr;
document.getElementById("errUser").innerHTML=errorUsernameEmpty;
document.getElementById("warnUser").innerHTML=warn;
return false;
}
else if ((!matchUsername.test(fld.value)) || (!matchUsername2.test(fld.value))) {
fld.style.border=borderErr;
document.getElementById("errUser").innerHTML=errorUsernameInvalid;
document.getElementById("warnUser").innerHTML=warn;
return false;
}
else {
document.getElementById("errUser").innerHTML="Username";
document.getElementById("warnUser").innerHTML="";
fld.style.border=borderOk;
return true;
}
}
// validate password
function validatePassword(fld) {
if (fld.value == "") {
fld.style.border=borderErr;
document.getElementById("errPass").innerHTML=errPassEmpty;
document.getElementById("warnPass").innerHTML=warn;
return false;
}
else if (!matchPass.test(fld.value)) {
document.getElementById("errPass").innerHTML=errPassInvalid;
document.getElementById("warnPass").innerHTML=warn;
fld.style.border=borderErr;
return false;
}
else {
fld.style.border=borderOk;
document.getElementById("errPass").innerHTML="Password";
document.getElementById("warnPass").innerHTML="";
return true;
}
}
// validate confirm password
function validatePassword2(fld) {
var passVal = document.getElementById("password").value;
if (fld.value == "") {
fld.style.border=borderErr;
document.getElementById("errPass2").innerHTML=errPassEmpty2;
document.getElementById("warnPass2").innerHTML=warn;
return false;
}
else if (passVal != fld.value) {
document.getElementById("errPass2").innerHTML=errPassInvalid2;
document.getElementById("warnPass2").innerHTML=warn;
fld.style.border=borderErr;
return false;
}
else {
fld.style.border=borderOk;
document.getElementById("errPass2").innerHTML="Confirm Password";
document.getElementById("warnPass2").innerHTML="";
return true;
}
}
// validate email address
function validateEmail(fld) {
if (fld.value == "") {
fld.style.border=borderErr;
document.getElementById("errEmail").innerHTML=errEmailEmpty;
document.getElementById("warnEmail").innerHTML=warn;
return false;
}
else if (!matchEmail.test(fld.value)) {
fld.style.border=borderErr;
document.getElementById("errEmail").innerHTML=errEmailInvalid;
document.getElementById("warnEmail").innerHTML=warn;
return false;
}
else {
fld.style.border=borderOk;
document.getElementById("errEmail").innerHTML="Email Address";
document.getElementById("warnEmail").innerHTML="";
return true;
}
}
As your inner validation methods return true or false, you need to modify your parent validation method to this or similar.
function validateForm(regForm) {
var formValid = true;
formValid &= validatefName(regForm.firstname);
formValid &= validateUsername(regForm.username);
formValid &= validatePassword(regForm.password);
formValid &= validatePassword2(regForm.password2);
formValid &= validateEmail(regForm.email);
if (!formValid) {
return false;
}
return true;
}
Try changing this line
var warning = "";
warning += validatefName(regForm.firstname);
warning += validateUsername(regForm.username);
warning += validatePassword(regForm.password);
warning += validatePassword2(regForm.password2);
warning += validateEmail(regForm.email);
if (warning != "") {
To this line
if(validatefName(regForm.firstname) == true && validateUsername(regForm.username) == true && validatePassword(regForm.password) == true && validatePassword2(regForm.password2) == true && validateEmail(regForm.email) == true) {
and see if it is correct now
Based on your fiddle, I found some errors in your code in the condition
if (title=="" || title==null) { } else {
alert("Please enter only alphanumeric values for your advertisement title");
}
Should be
if (title.length != 0) { } else {
alert("Please enter only alphanumeric values for your advertisement title");
return false;
}
The second is a more effective way to check if a field has no value.
I've also added return false in your else condition and the last return should be true.
here is your validateForm function. I updated your fiddle here
function validateForm() {
// Validate Email
var email = $("#fremail").val();
if ((/(.+)#(.+){2,}\.(.+){2,}/.test(email)) || email.length != 0) {
} else {
alert("Please enter a valid email");
return false;
}
// Validate Title
var title = $("#frtitle").val();
if (title.length != 0) {} else {
alert("Please enter only alphanumeric values for your advertisement title");
return false;
}
// Validate URL
var url = $("#frurl").val();
if (validateURL(url)) {} else {
alert("Please enter a valid URL, remember including http://");
return false;
}
return true;
}
Set a Flag = 1 in the function validateForm()
Increment Flag, if have validation error
End, return true, if Flag == 1 which means no error
function validateForm()
{
var flag = 1;
// Validate URL
var url = $("#frurl").val();
if (validateURL(url)) { } else {
alert("Please enter a valid URL, remember including http://");
flag++;
}
// Validate Title
var title = $("#frtitle").val();
if (title=="" || title==null) { } else {
alert("Please enter only alphanumeric values for your advertisement title");
flag++;
}
// Validate Email
var email = $("#fremail").val();
if ((/(.+)#(.+){2,}\.(.+){2,}/.test(email)) || email=="" || email==null) { } else {
alert("Please enter a valid email");
flag++;
}
if (flag == 1)
return true;
else
return false;
}
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).
Currently when new users register at my website, they have to fill out some forms. If their password is too short, doesn't match, they don't fill out all of the fields, or any other error, I want to alert them of it. Currently it does not alert them, so I switched to confirm. That didn't work either so I considered using showModalDiaglog. That also didn't work, I am out of Ideas. I currently have this:
HTML
<form>
First Name:<br/> <input id="firstname"/><br/>
Last Name: <br/> <input id="lastname"/><br/>
Age: <br/> <input id="age"/><br/>
Your Email:<br/> <input id="email"/><br/>
Username: <br/> <input id="username"/><br/>
Password: <br/> <input id="password"/><br/>
Confirm Password:<br/> <input type="password" id="passwordconfirm"/><br/>
<br/>
<button size=20 onClick='getRegistrationFields()'>Submit</button>
</form>
JavaScript
function getRegistrationFields() {
var first = document.getElementById("firstname").value;
var last = document.getElementById("lastname").value;
var email = document.getElementById("email").value;
var age = document.getElementById("age").value;
var username = document.getElementById("username").value;
var password = document.getElemetnById("password").value;
var confirm = document.getElementById("passwordconfirm").value;
var empty = "";
if ((first === empty) || (last === empty) || (email === empty) || (age === empty)
|| (username === empty) || (password === empty) || (confirm === empty)) {
var message = "Not all of the fields are filled out";
prompt(message);
//showModalWindow("fields");
return false;
}
else {
age = parseInt(age);
if (password.length < 10) {
var message2 = "Password must be at least 10 characters long";
prompt(message2);
//showModalWindow("passwordlength");
return false;
}
else if (password != confirm) {
var message3 = "Passwords Do not match";
prompt(message3);
//showModalWindow("passwordmatch");
return false;
}
else if (age < 18) {
var message4 = "You must be older to register for this software.";
prompt(message4);
//showModalWindow("young");
return false;
}
else {
var message5 = "All of the fields are correct. We will be processing your request";
prompt(message5);
//showModalWindow("success");
return true;
}
}
}
function showModalWindow(fileName) {
window.showModalDialog("alerts/" + url + ".html", "", "resizable: no; height: 150; width: 350;");
}
try
html:
<button size="20" id="btn_submit">Submit</button>
js:
var btn_submit = document.getElementById("btn_submit");
btn_submit.onclick = getRegistrationFields;
Make it easy on yourself.
<input type="password" class="password" />
<input type="text" class="age" />
<script type="text/javascript">
!(function () {
var txBxs = document.querySelectorAll('input[type=textbox]'),
i = txBxs.length;
while (i--) {
tkBxs[i].onchange = textBoxCheck;
};
}());
//
function textBoxCheck() {
//
switch (this.class) {
//
case 'password':
if (this.value.length < 10)
{ alert('Password to short'); };
break;
//
case 'age':
if (+this.value < 18)
{ alert('To young kiddo!'); };
break;
};
};
</script>
There is a typo:
var password = document.getElemetnById("password").value;
You wrote getElemetnById instead of getElementById.