Form Validation in Html & Javascript? - javascript

I am trying to validate my form with this javascript code, but this code firing the alert in case of any wrong input is entered, but my colleague says there should not be any alert. He says message should be show in front of textfield like below image. can anyone help me, How is it possible ?
My javascript and html code is
<script type="text/javascript">
function checkForm(form)
{
if(form.username.value == "") {
alert("Error: Username cannot be blank!");
form.username.focus();
return false;
}
re = /^\w+$/;
if(!re.test(form.username.value)) {
alert("Error: Username must contain only letters, numbers and underscores!");
form.username.focus();
return false;
}
if(form.pwd1.value != "" && form.pwd1.value == form.pwd2.value) {
if(form.pwd1.value.length < 6) {
alert("Error: Password must contain at least six characters!");
form.pwd1.focus();
return false;
}
if(form.pwd1.value == form.username.value) {
alert("Error: Password must be different from Username!");
form.pwd1.focus();
return false;
}
re = /[0-9]/;
if(!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one number (0-9)!");
form.pwd1.focus();
return false;
}
re = /[a-z]/;
if(!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one lowercase letter (a-z)!");
form.pwd1.focus();
return false;
}
re = /[A-Z]/;
if(!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one uppercase letter (A-Z)!");
form.pwd1.focus();
return false;
}
} else {
alert("Error: Please check that you've entered and confirmed your password!");
form.pwd1.focus();
return false;
}
alert("You entered a valid password: " + form.pwd1.value);
return true;
}
</script>
<form ... onsubmit="return checkForm(this);">
<p>Username: <input type="text" name="username"></p>
<p>Password: <input type="password" name="pwd1"></p>
<p>Confirm Password: <input type="password" name="pwd2"></p>
<p><input type="submit"></p>
</form>

Instead of alert(), you should write your own message display function. First, you need to add that error message container element in your html:
<form ... onsubmit="return checkForm(this);">
<p>Username: <input type="text" name="username"></p>
<p>Password: <input type="password" name="pwd1"></p>
<p>Confirm Password: <input type="password" name="pwd2"></p>
<p id="error-message-container" color="red"></p>
<p><input type="submit"></p>
</form>
And in Javascript part, you need to define an error display method which displays this error text inside error-message-container element:
function displayError(msg){
document.getElementById('error-message-container').innerHTML = msg;
}
Now you are ready to use displayError function instead of alert(), wherever you want to show an error like:
if(!re.test(form.username.value)) {
displayError("Error: Username must contain only letters, numbers and underscores!");
form.username.focus();
return false;
}

What you need is to insert a blank DIV after each input, and your javascript will insert error messages into them:
<script type="text/javascript">
function checkForm(form)
{
if(form.username.value == "") {
document.getElementById("username_error").innerHTML=("Error: Username cannot be blank!");
form.username.focus();
return false;
}
re = /^\w+$/;
if(!re.test(form.username.value)) {
document.getElementById("username_error").innerHTML=("Error: Username must contain only letters, numbers and underscores!");
form.username.focus();
return false;
}
if(form.pwd1.value != "" && form.pwd1.value == form.pwd2.value) {
if(form.pwd1.value.length < 6) {
document.getElementById("pwd1_error").innerHTML=("Error: Password must contain at least six characters!");
form.pwd1.focus();
return false;
}
if(form.pwd1.value == form.username.value) {
document.getElementById("pwd1_error").innerHTML=("Error: Password must be different from Username!");
form.pwd1.focus();
return false;
}
re = /[0-9]/;
if(!re.test(form.pwd1.value)) {
document.getElementById("pwd1_error").innerHTML=("Error: password must contain at least one number (0-9)!");
form.pwd1.focus();
return false;
}
re = /[a-z]/;
if(!re.test(form.pwd1.value)) {
document.getElementById("pwd1_error").innerHTML=("Error: password must contain at least one lowercase letter (a-z)!");
form.pwd1.focus();
return false;
}
re = /[A-Z]/;
if(!re.test(form.pwd1.value)) {
document.getElementById("pwd1_error").innerHTML=("Error: password must contain at least one uppercase letter (A-Z)!");
form.pwd1.focus();
return false;
}
} else {
document.getElementById("pwd1_error").innerHTML=("Error: Please check that you've entered and confirmed your password!");
form.pwd1.focus();
return false;
}
document.getElementById("pwd1_error").innerHTML=("You entered a valid password: " + form.pwd1.value);
return true;
}
</script>
<form ... onsubmit="return checkForm(this);">
<p>Username: <input type="text" name="username"><div id="username_error"></div></p>
<p>Password: <input type="password" name="pwd1"><div id="pwd1_error"></div></p>
<p>Confirm Password: <input type="password" name="pwd2"></p>
<p><input type="submit"></p>
</form>

I suggest JQuery validation plugin:
http://jqueryvalidation.org/
Demo:
http://jqueryvalidation.org/files/demo/

Related

I want to make a registration form but the script wont work the way i want

To validate the checkpoint the form will have to show an alert if
One of the inputs is empty
The password has less than 8 characters
Doesn't have a valid e-mail adress
The password must be a combination of charatacters , numbers and at least a capital letter
And finally the reset button will reset all the inputs to empty :
//Variable declaration
var username=document.forms["Registration"]["name"];
var e_mail=document.forms["Registration"]["email"];
var password=document.forms["Registration"]["psw1"];
var passwordcheck=document.forms["Registration"]["psw2"];
//add eventListener
username.addEventListener("blur", NameVerify, true);
e_mail.addEventListener("blur", EmailVerify, true);
password.addEventListener("blur", PasswordVerify, true);
passwordcheck.addEventListener("blur", PasswordVerify, true);
// validate the registration
function Validate(){
if (username.value=="")
{
alert("username is required");
username.focus()
return false;
}
if (e_mail.value=="")
{
alert("Email is required");
e_mail.focus()
return false;
}
if (password.value=="")
{
alert("Password is required");
password.focus()
return false;
}
if (passwordcheck.value=="")
{
alert("Re-enter your password");
passwordcheck.focus()
return false;
}
if(password.value != passwordcheck.value){
alert("Password do not match!!")
passwordcheck.focus()
return false;
}
}
//check the username value
function NameVerify(username){
if (username.value !=0) {
document.querySelector.backgroundColor = lightGrey;
return true;
}
}
//check the e_mail
function EmailVerify(e_mail){
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.`\w{2,3})+$/.test(Registration.email.value))`
{
return (true)
}
alert("You have entered an invalid email address!")
e_mail.focus()
return (false)
}
//check the password
function PasswordVerify(password){
var psw = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,20}$/;
if(password.value.match(psw))
{
alert('Correct, try another...')
return true;
}
else
{
alert('Wrong!!')
return false;
}
}
// clear all text inputs when the page is loaded
function clearInp() {
document.getElementsByTagName("input").value = "";
return true;
}
//reset all text fields
function Reset() {
document.querySelector("#Registration").reset();
return true;
}
None of this requires any JavaScript at all.
One of the inputs is empty
<input type="text" required />
The password has less than 8 characters
<input type="password" minlength="8" />
Doesn't have a valid e-mail adress
<input type="email" />
The password must be a combination of charatacters , numbers and at least a capital letter
<input type="password" pattern="(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}" />
And finally the reset button will reset all the inputs to empty
<input type="reset" value="Reset form" />
Once you've eliminated all JavaScript code from your form, you will find that your form no longer has any JavaScript errors ;)

Form validation click event fires on all inpout fields prematurely. I aslo need help to to store and compare sign in to login at later point

I am having trouble with validating my form inputs on my click event. The click event fires in each of my inputs on my form which then checks for validation before all fields are filled. I need to be able to submit and check for validation at the same event. Ive tried so many things I cant list them all.
I see that my click event needs to be on my anchor tag with the submit image or all inputs will respond to click event, but the username and password will not validate when I put a onclick="return checkForm(this); in the opening anchor tag. I also tried changing my anchor tag to a button and a div. I tried using jquery to make it work and failed.
I ultimately need the password and username to be stored and code written to check for login validation as well...
I have considered many different ways and each have failed.To many to list.
Help!
Having a alert pop up each time the user switches inputs is very anoying indeed.
I am new at this so I apologize for any incorrect or unorthodox coding and posting. Corrections and advice is welcomed and all assistance is appreciated greatly.
My code follows:
<!DOCTYPE html><!--this is where I got my password info-->
<html lang="en"><!--http://www.the-art-of-web.com/javascript/validate-password/#box1-->
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/jquery_library.js"></script>
<script type="text/javascript">
alert("Sign up please");
function checkForm(form)
{
if(form.username.value == "") {
alert("Error: Username cannot be blank!");
form.username.focus();
return false;
}
re = /^\w+$/;
if(!re.test(form.username.value)) {
alert("Error: Username must contain only letters, numbers and underscores!");
form.username.focus();
return false;
}
if(form.pwd1.value != "" && form.pwd1.value == form.pwd2.value) {
if(form.pwd1.value.length < 6) {
alert("Error: Password must contain at least six characters!");
form.pwd1.focus();
return false;
}
if(form.pwd1.value == form.username.value) {
alert("Error: Password must be different from Username!");
form.pwd1.focus();
return false;
}
re = /[0-9]/;
if(!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one number (0-9)!");
form.pwd1.focus();
return false;
}
re = /[a-z]/;
if(!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one lowercase letter (a-z)!");
form.pwd1.focus();
return false;
}
re = /[A-Z]/;
if(!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one uppercase letter (A-Z)!");
form.pwd1.focus();
return false;
}
} else {
alert("Error: Please check that you've entered and confirmed your password!");
form.pwd1.focus();
return false;
}
alert("You entered a valid password: " + form.pwd1.value);
return true;
}
</script>
/*clears my inputs*/
<script>
$(document).ready(function() {
$('input' ).on('click focusin', function() {
this.value = '';
});
});
</script>
/*enters my password into a variable for storage and futer login validation */
/*I amdoing the same thing for my username later...*/
<script>
$(document).ready(function() {
$('img[name="mySubmitButton"]').on('click focusin', function() {
$('input[name="passwordHolder"]').val($('input[name="pwd1"]').val());
});
});
</script>
</head>
<body>
<input style="visibility:hidden;" type="text" name="passwordHolder" value="This is your saved pasword:"/>
<h1>user sign in</h1>
<h2>You must complete and submit the form to get back to home page</h2>
<form onclick="return checkForm(this);">
<p>Username: <input type="text" name="username" value="enter your user name." autofocus="autofocus"></p>
<p>Password: <input type="password" name="pwd1"id="myPassword" ></p>
<p>Confirm Password: <input type="password" name="pwd2"></p>
<p><img src="img/submitButtonExitOverlayNewsletter.png" name="mySubmitButton" value="submit" value="Re-enter your password."/></p>
home Page
</form>
</body>
</html>
You have to use onsubmit instead of onclickand add <input type="submit" /> for onsubmit to work
If you want to style the submit button refer how-can-i-make-my-input-type-submit-an-image
For resetting of form use document.getElementById('myform').reset();
<!DOCTYPE html><!--this is where I got my password info-->
<html lang="en"><!--http://www.the-art-of-web.com/javascript/validate-password/#box1-->
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
alert("Sign up please");
function checkForm(form)
{
if(form.username.value == "") {
alert("Error: Username cannot be blank!");
form.username.focus();
return false;
}
re = /^\w+$/;
if(!re.test(form.username.value)) {
alert("Error: Username must contain only letters, numbers and underscores!");
form.username.focus();
return false;
}
if(form.pwd1.value != "" && form.pwd1.value == form.pwd2.value) {
if(form.pwd1.value.length < 6) {
alert("Error: Password must contain at least six characters!");
form.pwd1.focus();
return false;
}
if(form.pwd1.value == form.username.value) {
alert("Error: Password must be different from Username!");
form.pwd1.focus();
return false;
}
re = /[0-9]/;
if(!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one number (0-9)!");
form.pwd1.focus();
return false;
}
re = /[a-z]/;
if(!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one lowercase letter (a-z)!");
form.pwd1.focus();
return false;
}
re = /[A-Z]/;
if(!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one uppercase letter (A-Z)!");
form.pwd1.focus();
return false;
}
} else {
alert("Error: Please check that you've entered and confirmed your password!");
form.pwd1.focus();
return false;
}
//Use this to reset your form
// document.getElementById('myform').reset();
alert("You entered a valid password: " + form.pwd1.value);
return true;
}
</script>
/*clears my inputs*/
<script>
//You don't have to use this this will reset your values even on click and focusin
// $(document).ready(function() {
// $('input' ).on('click focusin', function() {
// this.value = '';
// });
// });
</script>
/*enters my password into a variable for storage and futer login validation */
/*I amdoing the same thing for my username later...*/
<script>
$(document).ready(function() {
$('img[name="mySubmitButton"]').on('click focusin', function() {
$('input[name="passwordHolder"]').val($('input[name="pwd1"]').val());
});
});
</script>
</head>
<body>
<input style="visibility:hidden;" type="text" name="passwordHolder" value="This is your saved pasword:"/>
<h1>user sign in</h1>
<h2>You must complete and submit the form to get back to home page</h2>
<form onsubmit="return checkForm(this);" id="myform">
<p>Username: <input type="text" name="username" value="enter your user name." autofocus="autofocus"></p>
<p>Password: <input type="password" name="pwd1"id="myPassword" ></p>
<p>Confirm Password: <input type="password" name="pwd2"></p>
<p><img src="img/submitButtonExitOverlayNewsletter.png" name="mySubmitButton" value="submit" value="Re-enter your password."/></p>
home Page
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>

Password input validation does not work inside form inputs validation code

I have a form using javascript input validation. I also wanted to add a password input to my form. But the problem now is that I ended up with two submit forms and one of them did not work. Then I tried to add my javascript validation code to the existing validation code for the form inputs. But when I ran test it did not work either. Can someone please point out what is wrong with my code? Here it is:
Here is the JavaScript code:
<script language="javascript">
function check() {
verify_code = document.getElementById("verify_code");
code = document.getElementById("code");
x = document.form1;
if (x.name.value=="") {
alert ("Please enter your Full Name!");
document.form1.name.focus ( )
return false;
}
else if (x.applicant_type.value=="") {
alert("Please select Applicant Type");
document.form1.applicant_type.focus ( )
return false;
}
else if(form1.pwd.value != "" && form1.pwd.value == form1.pwd1.value) {
if(form1.pwd.value.length < 6) {
alert("Error: Password must contain at least six characters!");
form1.pwd.focus();
return false;
}
re = /[0-9]/;
if(!re.test(form1.pwd.value)) {
alert("Error: password must contain at least one number (0-9)!");
form1.pwd.focus();
return false;
}
re = /[a-z]/;
if(!re.test(form1.pwd.value)) {
alert("Error: password must contain at least one lowercase letter (a-z)!");
form1.pwd.focus();
return false;
}
re = /[A-Z]/;
if(!re.test(form1.pwd.value)) {
alert("Error: password must contain at least one uppercase letter (A-Z)!");
form1.pwd.focus();
return false;
}
} else {
alert("Error: Please check that you've entered and confirmed your password!");
form1.pwd.focus();
return false;
}
alert("You entered a valid password: " + form1.pwd.value);
}
else
{ return true; }
}
</script>
And here is my password input code:
<br>Password:<span class="style4">*</span> <input type="password" name="pwd"><br>
<br>Confirm Password:<span class="style4">*</span> <input type="password" name="pwd1"><br>
<span class="formnotes">(For future use if you need to modify your application) </span>
My password input validation works if I use this code:
Javascript:
<script type="text/javascript">
function checkForm(form)
{
if(form.username.value == "") {
alert("Error: Username cannot be blank!");
form.username.focus();
return false;
}
re = /^\w+$/;
if(!re.test(form.username.value)) {
alert("Error: Username must contain only letters, numbers and underscores!");
form.username.focus();
return false;
}
if(form.pwd1.value != "" && form.pwd1.value == form.pwd2.value) {
if(form.pwd1.value.length < 6) {
alert("Error: Password must contain at least six characters!");
form.pwd1.focus();
return false;
}
if(form.pwd1.value == form.username.value) {
alert("Error: Password must be different from Username!");
form.pwd1.focus();
return false;
}
re = /[0-9]/;
if(!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one number (0-9)!");
form.pwd1.focus();
return false;
}
re = /[a-z]/;
if(!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one lowercase letter (a-z)!");
form.pwd1.focus();
return false;
}
re = /[A-Z]/;
if(!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one uppercase letter (A-Z)!");
form.pwd1.focus();
return false;
}
} else {
alert("Error: Please check that you've entered and confirmed your password!");
form.pwd1.focus();
return false;
}
alert("You entered a valid password: " + form.pwd1.value);
return true;
}
</script>
And HTML:
<form ... onsubmit="return checkForm(this);">
<p>Username: <input type="text" name="username"></p>
<p>Password: <input type="password" name="pwd1"></p>
<p>Confirm Password: <input type="password" name="pwd2"></p>
<p><input type="submit"></p>
</form>
But when I use this code onSubmit="return check();" it is not working

Error in code using javascript

The code I have for my username and password verification is bringing up an error and im not sure how to fix it
I am trying to use
function checkForm(form) {
if (form.username.value == "") {
alert("Error: Username cannot be blank!");
form.username.focus();
return false;
}
re = /^\w+$/;
if (!re.test(form.username.value)) {
alert("Error: Username must contain only letters, numbers and underscores!");
form.username.focus();
return false.pwd2.value) {
if (form.pwd1.value.length < 8) {;
}
if (form.pwd1.value != "" && form.pwd1.value == form alert("Error: Password must contain at least eight characters!"); form.pwd1.focus();
return false;
}
if (form.pwd1.value == form.username.value) {
alert("Error: Password must be different from Username!");
form.pwd1.focus();
return false;
}
re = /[0-9]/;
if (!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one number (0-9)!");
form.pwd1.focus();
return false;
}
re = /[a-z]/;
if (!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one lowercase letter (a-z)!");
form.pwd1.focus();
return false;
}
re = /[A-Z]/;
if (!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one uppercase letter (A-Z)!");
form.pwd1.focus();
return false;
}
} else {
alert("Error: Please check that you've entered and confirmed your password!");
form.pwd1.focus();
return false;
}
alert("You entered a valid password: " + form.pwd1.value);
return true;
}
I am trying to use this code for this html
<form name="hw4Form" action="" autocomplete="off">
<br>
<fieldset name="LoginInfo">
<input id="username" type="text" name="username" placeholder="username" size="30">
<br>
<br>
Password:
<br>
<input id="pwd1" type="password" name="pwd1" placeholder="password" required="required" size="30">
<span id="pwd1Hint" class="hint">Password is too short (must be at least 8 characters)</span>
<br>
Repeat Password:
<br>
<input id="pwd2" type="password" name="pwd2" placeholder="password" required="required" size="30">
<span id="pwd2Hint" class="hint">Passwords don't match</span>
<br>
<br>
I get a error in my code editing software but I cant figure out how to fix it
I also would just like to make sure that this javascript will work for the html
Looks like this line:
if(form.pwd1.value != "" && form.pwd1.value == form
should be:
if(form.pwd1.value != "" && form.pwd1.value == form.username.value)) {
or something similar to this.
In your html you also need to close your form with </form>
I advice u using console.log(form) or other fields to check the js performing process.Or why not use firebug to debug the function.

Validating Password

I'm trying to validate a password using javascript, It's to make sure that when changing the password, the new password entered is equal to that of the re-entering of the new password (user is asked to enter their new password twice so both have to match) but at the same time, i want to make sure that the new password is at least 6 characters long, I have these functions separately but don't know how to combine them... thanks for help in advance!
This is what i have so far...
This is to make sure the new passwords match:
function validatePassword()
{
var new_password = document.getElementById("new_password").value;
var confirm_new_password = document.getElementById("confirm_new_password").value;
<!-- if they match, go to next page -->
if ( new_password == confirm_new_password)
{
return true;
}
<!-- if they don't match, an error message is displayed -->
else
{
alert("Passwords do not match.");
}
return false;
}
This is for length of password:
function validatePassword()
{
if (document.getElementById("new_password").value.length < "5")
{
<!--If pasword is less than 5 characters long, display error message-->
alert("Please ensure your password is at least 6 characters long.");
return false;
}
return true;
}
How do i combine both of these to form a SINGLE function where the two new passwords are checked so that they match, and also check that they are longer than 6 characters?
To just combine your two functions, this would work:
function validatePassword()
{
var new_password = document.getElementById("new_password").value;
var confirm_new_password = document.getElementById("confirm_new_password").value;
if (new_password.length < 5)
{
<!--If pasword is less than 5 characters long, display error message-->
alert("Please ensure your password is at least 6 characters long.");
return false;
}
else if ( new_password != confirm_new_password)
{
alert("Passwords do not match.");
return false;
}
else
{
return true;
}
}
Although I agree, there are better procedures out there. And please, make sure you're doing server-side validation as well since client-side validation is very easy to skip around.
i m not sure but you can call validatePassword() this function inside
if ( new_password == confirm_new_password)
{
validatePassword();
}
You have two options, either make the two functions a single function, or make them two separate functions and call them both before you submit / process your form.
if (validatePasswordLength() && validatePasswordsMatch()) {
// Continue
}
you have to try this code that is small and working.
if(document.getElementById("new_password").value != document.getElementById("confirm_new_password").value){
alert("Passwords do not match.");
return false;
}
<script>
function validatePassword()
{
var new_password = document.getElementById("new_password").value;
var confirm_new_password = document.getElementById("confirm_new_password").value;
if (document.getElementById("new_password").value.length < "5")
{
alert("Please ensure your password is at least 6 characters long.");
return false;
}
if (new_password == confirm_new_password)
{
alert("Password no match");
return false;
}
return true;
}
</script>
<form action="" onsubmit="return validatePassword()">
<p>New Password: <input type="password" id="new_password" name="new_password" /></p>
<p>Confirm Password: <input type="password" id="confirm_new_password" name="confirm_new_password" /></p>
<p><input type="submit" value="submit" /></p>
</form>

Categories