Password Validation javascript - javascript

I am trying to create a very very basic profile page using Name, Email, Username, and Password. I have to have a password validation code/button.
The home page will be very similar to a common profile page. The user must be able to input the following:
Name field
Email field
User ID field
Password field 3
Validation Password field
The following buttons are required:
Password validation button
Create Profile button
I can put it all together, but the problem I am having is that the javascript console is telling me that there are some errors in the code...
function validate(){
var pass1 = document.getElementById('password');
var pass2 = document.getElementById('Password2');
if (pass1 == pass2)
{
alert("Passwords Match")
}
else
{
alert("Passwords Do Not Match")
}
}
<head>
<script type="text/javascript" src="Profile Page.js"></script>
</head>
<body>
Enter First and Last Name
<input type="text" id="name">
<br>Enter Your Email Address
<input type="text" id="email">
<br>Please Enter a Username
<input type="text" id="username">
<br>Please Enter a Password
<input type="password" id="password">
<br>Enter Your Password Again
<input type="Password" id="password2">
<br>
<button type="button" id="validate" onClick="validate()">Validate Password</button>
<button type="button" id="create" onClick="submit()">Create Profile</button>
</body>
Ok, so I figured out where my errors were, now the alert that I set up for the passwords not matching is coming up, even when the passwords are the same thing. Any suggestions?

Please try it like this:
function validateForm(){
var pass1 = document.getElementsByName("password")[0].value;
var pass2 = document.getElementsByName("password2")[0].value;
if (pass1 === pass2) {
alert("Passwords Match");
} else {
alert("Passwords Do Not Match");
}
}
Enter First and Last Name
<input type = "text" id = "name" /><br/>
Enter Your Email Address
<input type = "text" id = "email" /><br/>
Please Enter a Username
<input type = "text" id = "username" /><br/>
Please Enter a Password
<input type = "password" name = "password" /><br/>
Enter Your Password Again
<input type = "Password" name= "password2" /><br/>
<button type = "button" id = "validate" onclick = "validateForm();">Validate Password</button>
<button type = "button" id = "create" onclick = "submit()">Create Profile</button>

Below is the generic function to validate password by comparing with repeat password, Contains lowercase, Contains uppercase, Contains digit
function validatePassword(password, repeatPassword){
var MinLength = 6;
var MaxLength = 15;
var meetsLengthRequirements:boolean = password.length >= MinLength && repeatPassword.length <= MaxLength;
var hasUpperCasevarter:boolean = false;
var hasLowerCasevarter:boolean = false;
var hasDecimalDigit:boolean = false;
if (meetsLengthRequirements)
{
for (var i = 0, len = password.length; i < len; i++) {
var char = password.charAt(i);
if (!isNaN( +char * 1)){
hasDecimalDigit = true;
}
else{
if (char == char.toUpperCase()) {
hasUpperCasevarter = true;
}
if (char == char.toLowerCase()){
hasLowerCasevarter = true;
}
}
}
}
var isValid = meetsLengthRequirements
&& hasUpperCasevarter
&& hasLowerCasevarter
&& hasDecimalDigit;
return isValid;
}

Related

passoword validation without jQuery

I am making a password validation using js and html. It suppose to show certain information under the input parts if the input is not valid. But whatever the input is, there's no message at all. I am not sure which part I did wrong. Code is posted below
var name = document.getElementById("userName");
var passWord = document.getElementById("passWord");
var flag;
function check() {
flag = validateInput(name, passWord);
if (flag)
isPaswordValid(passWord);
if (flag)
ispassWordStrong(passWord);
}
function validateInput(name, passWord) {
if (name.length = 0 || passWord.length < 0) {
document.getElementById("errorMessage").innerHTML = "Please enter Username and passWord";
return false;
}
else {
document.getElementById("errorMessage").innerHTML = "Valid input";
return true;
}
}
//Check Username and passWord are valid
function isPaswordValid(passWord) {
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
//Check passWord is valid or not and having length of passord should not less than 8
if (passWord.length < 8 || (!re.test(passWord))) {
document.getElementById("errorMessage").innerHTML = "Invalid passWord. Please enter new passWord";
return false;
}
else {
document.getElementById("errorMessage").innerHTML = "Valid input";
return true;
}
}
//Check password has no more than 3 characters from username in passWord
function ispassWordStrong(userName, passWord) {
var n = 0;
for (var i = 0; i < userName.length; i++) {
if (passWord.indexOf(userName[i]) >= 0) {
n += 1;
}
}
if (n > 3) {
document.getElementById("errorMessage").innerHTML = "passWord can't contain more than 3 characters from the username.";
}
else {
document.getElementById("errorMessage").innerHTML = "Valid input";
}
}
});
<body>
<fieldset>
<legend>Password Validator</legend>
User Name:
<input type="text" id="userName" name="userName" placeholder="User Name" onkeyup='check();' /><br>
passWord:
<input type="password" id="passWord" name="passWord" placeholder="Password" onkeyup='check();' />
<input type="submit" id="inputValidate" value="Validate"><br /><br />
<b><span style="color:red;" id="errorMessage"></span></b>
</fieldset>
</body>
Sorry for the long codes and thanks for your help.
The following should do what you require:
// collect all DOM elements in object ti: ti.i, ti.e, ti.u, ti.p
const ti=["inputValidate","errorMessage","userName","passWord"]
.reduce((a,c)=>(a[c.substr(0,1)]=document.querySelector('#'+c),a),{});
// delegated event listening for event "input":
document.querySelector('fieldset').addEventListener('input',ev=>{
if (Object.values(ti).indexOf(ev.target)>1){ // for userName and passWord do ...
let u=ti.u.value.toLowerCase();
ti.e.textContent= (ti.p.value.length > 2
&& ti.p.value.split('').reduce((a,c)=>a+=u.indexOf(c.toLowerCase())>-1?1:0,0) > 2 )
? "The password contains at least 3 letters from the username!" : "";
}})
// event listening for button click on "validate":
ti.i.addEventListener('click',ev=>!(ti.e.textContent=
(ti.u.value.trim().length ? "" : "User name is empty.") ||
(ti.p.value.match(/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/)
? "" : "The password is not complex enough!" )))
<fieldset>
<legend>Password Validator</legend>
User Name:<br/>
<input type="text" id="userName" name="userName" placeholder="User Name"/><br>
passWord:<br/>
<input type="password" id="passWord" name="passWord" placeholder="Password"/>
<input type="submit" id="inputValidate" value="Validate"><br/>
<b><span style="color:red;" id="errorMessage"></span></b>
</fieldset>
While inputting characters in the fields #userName and #passWord it checks for the occurence of user name characters in the password. This is done ignoring upper or lower case. And when clicking on the "validate" button the complexity of the password is checked against the regular expression /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/. This regular expression demands at least
one upper case chraracter,
one lower case character
one number and
a minimum length of 8.
There is also a rudimentary check on the user name. It must contain at least one non-blank character. The event handler for the click event on the "validate" button returns false whenever an error is detected. This can be used to prevent the submission of the form. However, the form itself was not supplied by OP.

How to retain the entered data in an html form after clicking submit

I have a form in an html page that ends up being cleared after i click the submit button. I wanted to know how I to make the data stay in the form after clicking submit in case the user needs to fix any errors. Any help would be appreciated!
Here is the html code:
<form id = "contactform" action = "">
<label> Name:
<input name = "firstname" type = "text" id = "firstname" maxlength = "50"/>
</label>
<label> Last Name:
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />
</label>
<label> Address:
<input name = "address" type = "text" id = "address" maxlength = "200"/>
</label>
<label> Postcode:
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />
</label>
<input type = "submit" value = "Submit" onclick = "validate()" />
<input type = "reset" value = "Clear" />
</p>
</form>
and here is the javascript code:
function validate() {
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var address = document.getElementById('address');
var postcode = document.getElementById('postcode');
if(firstname.value == "") {
alert("Make sure the first name field is filled");
return false;
}
if(lastname.value == "") {
alert("Make sure the last name field is filled");
return false;
}
if(address.value == "") {
alert("Make sure the address field is filled");
return false;
}
if(postcode.value == "") {
alert("Make sure the post code field is filled");
return false;
}
First, add a submit handler to your form:
<form id="contactform" action = "" onsubmit="handleSubmit()">
...
</form>
Then in your handler validate the input. If its not valid you need to preventDefault() to stop the form from submitting. Note: You'll have to return true at the end of validate() if nothing is wrong. I don't see that in the question.
function handleSubmit(event) {
if(!validate()) {
event.preventDefault();
}
return;
}
Add return with onclick onclick="return validate()"
function validate() {
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var address = document.getElementById('address');
var postcode = document.getElementById('postcode');
if (firstname.value == "") {
alert("Make sure the first name field is filled");
return false;
}
if (lastname.value == "") {
alert("Make sure the last name field is filled");
return false;
}
if (address.value == "") {
alert("Make sure the address field is filled");
return false;
}
if (postcode.value == "") {
alert("Make sure the post code field is filled");
return false;
}
}
<form id="contactform" action="">
<label> Name:
<input name = "firstname" type = "text" id = "firstname" maxlength = "50"/>
</label>
<label> Last Name:
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />
</label>
<label> Address:
<input name = "address" type = "text" id = "address" maxlength = "200"/>
</label>
<label> Postcode:
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />
</label>
<input type="submit" value="Submit" onclick="return validate()" />
<input type="reset" value="Clear" />
</form>

HTML form being reloaded and java script message not being displayed

I am a new to Javascript programming. I have developed the below script and encountering the below issues. Request the expert to help to resolve the issues.
Issues are
when both username and password are filled (username not equal to password) the javascript message displays and the form automatically reloads removing the message.
when username or password is left empty, the message being displayed is "Invalid username or password". The correct javascript message is not being displayed.
when both the fields are not filled the script executes successfully and "Welcome" is printed. If condition in javascript not being executed to display the correct message. Also have used "required" attribute to display the error "this field is required" but still "welcome' is being printed.
<!DOCTYPE html>
<html>
<head>
<script>
function verify() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if ((typeof username) == undefined) {
document.getElementById("message").innerHTML = "Username Required.";
}
if ((typeof password) == undefined) {
document.getElementById("message").innerHTML = "password Required.";
}
if (username == password) {
document.write("Welcome");
}
else {
document.getElementById("message").innerHTML = "Invalid Username or password";
}
}
</script>
</head>
<body>
<h1 style="text-align:center">Welcome to MEPC World!!</h1>
<br>
<form style="margin:auto;max-width:60%" >
<fieldset style="border:groove;border-width:5px;border-color:lightgrey;text-align:center">
<legend><b>Login</b></legend>
<p id="message" style="color:red;text-align:left"></p>
<br>
Username :
<input id="username" type="text" placeholder="username (e.g. XYZ)" autocomplete="off" required="required"> </input>
<br>
<br>
Password :
<input id="password" type="password" placeholder="password" required="required"> </input>
<br><br>
<input type="submit" value="Submit" onclick="verify()">
</fieldset>
</form>
<p><b>Note:</b> Username and password are case-sensitive.</p>
</body>
</html>
This is how you should be doing it. Or the message gets overridden because you have multiple if statements instead of an if/elseif/else which will only allow one to be true.
function verify() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username === undefined || username === '') {
document.getElementById("message").innerHTML = "Username Required.";
}
else if (password == undefined || password === '') {
document.getElementById("message").innerHTML = "password Required.";
}
// This doesn't make sense at all fyi
else if (username === password) {
document.write("Welcome");
}
else {
document.getElementById("message").innerHTML = "Invalid Username or password";
}
}
To prevent the form from submitting you have to do this:
<input type="submit" value="Submit" onclick="return verify()">

Javascript validation on my form not working properly

I want to make a form validation using JavaScript but its not working properly. Can someone please help me?
here is my code:
JavaScript
<script type="text/javascript">
var ck_name = /^[A-z]+$/;
var ck_email = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var ck_username = /^[A-Za-z0-9_]{1,20}$/;
var ck_password = /^[A-Za-z0-9!##$%^&*()_]{6,20}$/;
function validate()
{
var name = document.form.name;
var email = document.form.email;
var username = document.form.username;
var password = document.form.password;
if (!ck_name.test(name)) {
window.alert("You must enter valid Name .");
name.focus();
return false;
}
if (!ck_email.test(email)) {
window.alert("You must enter a valid email address.");
email.focus();
return false;
}
if (!ck_username.test(username)) {
window.alert("Your valid UserName does not contain any special char.");
username.focus();
return false;
}
if (!ck_password.test(password)) {
window.alert("You must enter a valid Password ");
password.focus();
return false;
}
return true;
}
</script>
HTML
<form action="#" name="form" onsubmit="return validate();">
<p>Name: <input type="text" size="25" name="name"/></p>
<p>E-mail: <input type="text" size="25" name="email"/></p>
<p>UserName: <input type="text" size="25" name="username"/></p>
<p>Password: <input type="text" size="25" name="password"/></p>
<p><input type="submit" value="Send" name="submit" />
<input type="reset" value="Reset" name="reset" /></p>
</form>
You need to get form from document here is what you should use
var name = document.forms[0].name.value;
var email = document.forms[0].email.value;
var username = document.forms[0].username.value;
var password = document.forms[0].password.value;
This will only get html element
var name=document.forms[0].name
You need to get its value.
var name=document.forms[0].name.value;
Update the js code to get the element value
var name = document.forms['form'].elements['name'].value;
var email = document.forms['form'].elements['email'].value;
var username = document.forms['form'].elements['username'].value;
var password = document.forms['form'].elements['password'].value;
You are checking input elements instead you need to check their value.
Here is the updated/working code.
function validate() {
var name = document.form.name;
var email = document.form.email;
var username = document.form.username;
var password = document.form.password;
if (!ck_name.test(name.value)) {
window.alert("You must enter valid Name .");
name.focus();
return false;
}
if (!ck_email.test(email.value)) {
window.alert("You must enter a valid email address.");
email.focus();
return false;
}
if (!ck_username.test(username.value)) {
window.alert("Your valid UserName does not contain any special char.");
username.focus();
return false;
}
if (!ck_password.test(password.value)) {
window.alert("You must enter a valid Password ");
password.focus();
return false;
}
return true;
}
You should get elements' value. I just made some changes and works properly. Try this:
var ck_name = /^[A-z]+$/;
var ck_email = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var ck_username = /^[A-Za-z0-9_]{1,20}$/;
var ck_password = /^[A-Za-z0-9!##$%^&*()_]{6,20}$/;
function validate() {
var name = document.form.name.value;
var email = document.form.email.value;
var username = document.form.username.value;
var password = document.form.password.value;
if (!ck_name.test(name)) {
window.alert("You must enter valid Name .");
name.focus();
return false;
}
if (!ck_email.test(email)) {
window.alert("You must enter a valid email address.");
email.focus();
return false;
}
if (!ck_username.test(username)) {
window.alert("Your valid UserName does not contain any special char.");
username.focus();
return false;
}
if (!ck_password.test(password)) {
window.alert("You must enter a valid Password ");
password.focus();
return false;
}
return true;
}
<form action="#" name="form" onsubmit="return validate();">
<p>Name:
<input type="text" size="25" name="name" />
</p>
<p>E-mail:
<input type="text" size="25" name="email" />
</p>
<p>UserName:
<input type="text" size="25" name="username" />
</p>
<p>Password:
<input type="text" size="25" name="password" />
</p>
<p>
<input type="submit" value="Send" name="submit" />
<input type="reset" value="Reset" name="reset" />
</p>
</form>

onSubmit Function not able to call a function inside of it

I am trying to make a form. I want it to check the radio buttons to see if they have been clicked, and if not to have a message to the user to check one.
I tried to just enter it, then I tried to continue my else if statements with it (got error messages), then I tried making a function within the onsubmit function (it simply didn't initiate), then I tried making a function outside of the onsubmit function and am trying to call it, but it does not initiate. I've even tried moving the functions on top or below the onsubmit function.
I made the submitYesCancel to see if the problem was with the radioB function, but neither function will initiate.
I'm hopelessly stuck. Please help.
Here is the code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title></title>
<script type="text/javascript">
/* <![CDATA[ */
function confirmPassword()
{
if (document.forms[0].password_confirm.value != document.forms[0].password.value)
{
window.alert("You did not enter the same password!");
document.forms[0].password.focus();
}
}
function submitForm()
{
submitYesCancel();
if (document.forms[0].name.value == ""
|| document.forms[0].name.value == "Your Name")
{
window.alert("You must enter your name.");
return false;
}
else if (document.forms[0].emailAddress.value == ""
|| document.forms[0].emailAddress.value == "Your Email")
{
window.alert("You must enter your email address.");
return false;
}
else if (document.forms[0].password.value == ""
|| document.forms[0].password_confirm.value == "")
{
window.alert("You must enter a password.");
return false;
}
else if (document.forms[0].sq.value ==""
|| document.forms[0].sq.value == "Your Security Answer")
{
window.alert("You must enter a security answer.");
return false;
}
radioB();
return true;
}
function submitYesCancel()
{
var submitForm = window.confirm("Are you sure you want to submit the form?");
if (submitForm == true)
{
return true;
return false;
}
}
function radioB()
{
var radioButton = false;
for (var i = 0; i < 4; ++i)
{
if (document.forms[0].special_offers[i].checked == true)
{
radioButton = true;
break;
}
}
if (radioButton != true)
{
window.alert("You must select a radio button.");
return false;
}
}
function confirmReset()
{
var resetForm = window.confirm("Are you sure you want to reset the form?");
if (resetForm == true)
return true;
return false;
}
/* ]]> */
</script>
</head>
<body>
<form>
<h2>Personal Information</h2>
<p>Name:<br />
<input type = "text" name = "name" placeholder = "Your Name" size = "50"/></p>
<p>Email Address:<br />
<input type = "text" name = "emailAddress" placeholder = "Your Email" size= "50" /></p>
<h2>Security Information</h2>
<p>Please enter a password of 8 characters or less: <br />
<input type = "password" name = "password" maxlength = "8" /></p>
<p>Confirm password<br />
<input type = "password" name = "password_confirm" size = "50" onblur = "confirmPassword();" /></p>
<p>Please Select a Security Question from the Drop Down List.<br />
<select name = "Security Question">
<option value = "mother">What is your Mother's maiden name?</option>
<option value = "pet">What is the name of your pet?</option>
<option value = "color">What is your favorite color?</option>
</select></p>
<p><input type = "text" name = "sq" placeholder = "Your Security Answer" size = "50" /></p>
<h2>Preferences</h2>
<p>Would you like special offers sent to your email address?<br />
<input type = "radio" name = "radioButton" value = "Yes" />Yes<br />
<input type = "radio" name = "radioButton" value = "No" />No<br /></p>
<p>Are you interested in special offers from: <br />
<input type = "checkbox" name = "sCheckboxes" value = "e" />Entertainment<br />
<input type = "checkbox" name = "sCheckboxes" value = "b" />Business<br />
<input type = "checkbox" name = "sCheckboxes" value = "s" />Shopping<br /></p>
<button onclick="return submitForm();">Submit</button>
<button onclick="return confirmReset();">Reset</button>
</form>
</body>
</html>
The reason that it does not work because your Javascript is completely wrong.
}
radioB();
else // <--- what does it mean?
return true;
And
else if (radioButton ! = true) {
// <-- you have else if, but there is no if block and it is != not ! =
Next time when your Javascript does not work, try to see the error first. You can easily do this in Google Chrome. Hit Ctrl + Shift + J, go to Console tab. Then, fix each error when you encounter it until there is no more error.

Categories