John John - 2 years ago 92
Javascript Question

JS send message on correct input

I have a submit form that users are using to register:

<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>" name="form" onSubmit="return validate(this);">
<div class="form-group">
<input type="text" id="name" name="name" class="inputs" /><br />
<input type="text" id="email" name="email" class="inputs" /><br />
<input type="password" id="password" name="password" class="inputs" />
<input type="submit" class="btn1" name="register" value="Register" />

The JS code is checking if the data is entered correctly. If the user enters incorrect date the JS code is showing a message. Now I want to show a message when the data is entered correctly. I tried to add a row like
if (errors.length < 0)
but this didn't work. The JS code sends me the message for the "correct input" and the message "Dont use symbols...\n".

How can I make this working?

Here is my JS code:

<script type="text/javascript">
var ck_name = /[A-Za-z0-9. ]{3,25}$/;
var ck_email = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var ck_password = /^[A-Za-z0-9!@#$%^&*()_]{6,20}$/;

function validate(form)
var name =;
var email =;
var password = form.password.value;

var errors = [];

if (!ck_name.test(name))
errors[errors.length] = "Name error! .";

if (!ck_email.test(email))
errors[errors.length] = "Email error! .";

if (!ck_password.test(password))
errors[errors.length] = "Password error!";

if (errors.length > 0)
return false;

return true;

function reportErrors(errors)
var msg = "Dont use symbols...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];

Answer Source

Errors.length never won't be minor of 0. You must use equal (==). This works! :-)


if (errors.length == 0) {
 alert('Correct input');

That would be before the return true statement and after the if (errors.length > 0).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download