I am unable to print a single output statement when there is no match. At the moment, if there is no match (no number incl. in password) it will print out multiple times until it does find a match.
Could anyone take a look at my dilemma below please:
var password = "password1";
var i = 0;
function checkPassword(password) {
if (password === "") {
console.log("password cannot be empty");
} else if (password.length < 8) {
console.log("password should be at least 7 characters");
} else {
while (i < password.length) {
if (password[i] == password.match(/[0-9]/g)) {
console.log("found: " + password[i]);
} else {
console.log("not found");
}
i++;
}
}
}
var password = "password1";
var i = 0;
function checkPassword(password) {
if (password === "") {
console.log("password cannot be empty");
} else if (password.length < 8) {
console.log("password should be at least 7 characters");
} else {
var found = false;
while (i < password.length) {
if (password[i].match(/[0-9]/g)) {
found = true;
break;
}
i++;
}
if(found) {
console.log("found");
} else {
console.log("not found");
}
}
}
But, if you are only looking for a number in the string, you should better do it like this:
var password = "password1";
function checkPassword(password) {
if (password === "") {
console.log("password cannot be empty");
} else if (password.length < 8) {
console.log("password should be at least 7 characters");
} else if(!password.match(/[0-9]{1,}/)) {
console.log("password should contain at least one number");
} else {
console.log("okay");
}
}
Here is a JSFiddle: https://jsfiddle.net/7btt1axb/
Something like this?
var password = "password1";
function checkPassword(password) {
if (password === "") {
console.log("password cannot be empty");
} else if (password.length < 8) {
console.log("password should be at least 7 characters");
} else {
var i = 0, found = false;
while (i < password.length && !found) {
if (password[i] == password.match(/[0-9]/g)) found = true;
else i++;
}
if (found) {
console.log("found: " + password[i]);
} else console.log("not found");
}
}
checkPassword(password);
Related
I wrote this code for validate password and i need to show user two different alerts.
(pw.length < 8) when this condition executed "Password need minimum 8 characters"
(pw != cpw) "Passwords does not match"
I already tried all if statements but it not gonna help.
<script>
function validatePassword(){
var pw= document.getElementById("txtPassword").value;
var cpw= document.getElementById("txtCPassword").value;
if((pw.length < 8)||(pw != cpw))
{
alert("please enter the correct password")
return false;
Event.preventDefault();
}
return true;
}
</script>
Does anyone know if something...
Use a boolean and two if statements. Return the boolean at the end for true or false.
function validatePassword() {
const pw = document.getElementById("txtPassword").value;
const cpw = document.getElementById("txtCPassword").value;
let isValid = true;
if (pw.length < 8) {
alert('Password is not long enough. Minimum length is 8 characters.');
isValid = false;
}
if(pw !== cpw)) {
alert('Passwords do not match'.);
isValid = false;
}
return isValid;
}
Or have both messages in one alert using an array
function validatePassword() {
const pw = document.getElementById("txtPassword").value;
const cpw = document.getElementById("txtCPassword").value;
const errors = [];
if (pw.length < 8) {
errors.push('Password is not long enough. Minimum length is 8 characters.');
}
if(pw !== cpw)) {
errors.push('Passwords do not match.');
}
if (errors.length) {
alert(errors.join('\n'));
return false;
}
return true;
}
here is most basic version you can use this type of code.
function validatePassword(){
var pw= document.getElementById("txtPassword").value;
var cpw= document.getElementById("txtCPassword").value;
if((pw.length < 8))
{
alert("please enter the correct password")
return false;
} else if((cpw != pw)) {
alert("Passwords does not match")
} else {
alert("Password is correct!")
return true;
}
}
<form id="form">
<input type="text" id="txtPassword">
<input type="text" id="txtCPassword">
<input onclick="event.preventDefault();validatePassword()" type="submit" value="Submit">
</form>
This will do.
<script>
var pw= document.getElementById("txtPassword").value;
var cpw= document.getElementById("txtCPassword").value;
function validatePassword(){
if(pw.length < 8)
{
alert("Password need minimum 8 characters")
}
if(pw != cpw){
alert("Passwords does not match")
}
}
I don't think you need to show 2 alerts. When txtPassword is invalid, users have to retype both passwords whether passwords match or not. There is no point in showing "Passwords does not match" message in that case.
To know how to show 2 alerts, see my second code.
First, here is another solution:
const FORM = document.querySelector('#form');
const PSW = document.querySelector('#txtPassword');
const C_PSW = document.querySelector('#txtCPassword');
FORM.addEventListener('submit', event => {
event.preventDefault();
if (!validatePassword()) return;
console.log('Submitted');
})
function validatePassword() {
let pw = PSW.value;
let cpw = C_PSW.value;
if (pw.length < 8) {
alert('please enter the correct password');
return;
} else if (pw !== cpw) {
alert('Passwords does not match');
return;
}
return true;
}
<form action="" id="form">
<input type="password" id="txtPassword">
<input type="password" id="txtCPassword">
<input type="submit" value="Submit">
</form>
To show 2 alerts:
function validatePassword() {
let pw = PSW.value;
let cpw = C_PSW.value;
if (pw.length < 8) {
alert('please enter the correct password');
if (pw !== cpw) {
alert('Passwords does not match');
}
return;
} else if (pw !== cpw) {
alert('Passwords does not match');
return;
}
return true;
}
The third log doesn't go through, does anyone know why??
I've been trying to figure out for a while, and I've been struggling a lot.
var KnowsUsername = true;
var KnowsEmail = true;
var KnowsPassword = true;
setTimeout(function(){
var Username = prompt('What is your username?');
if(Username == '') {
KnowsUsername = true;
console.log("Correct username!");
} else {
KnowsUsername = false;
console.error('\x1b[31m%s\x1b[0m', 'Aww! wrong username! try again!');
}
if (KnowsUsername == false) {
return;
} else {
if (KnowsUsername == true) {
var Email = prompt('What is your E-mail?');
if(Email == '') {
KnowsEmail = true;
console.log("Correct E-mail!");
} else {
KnowsEmail = false;
console.error('\x1b[31m%s\x1b[0m', 'Wrong E-mail! try again!');
}
}
if (KnowsEmail == false) {
return;
} else {
if (KnowsEmail == true) {
var Password = prompt('What is your password?');
if (!Password == '') {
KnowsPassword = false;
console.error('\x1b[31m%s\x1b[0m', 'Aww! wrong password! try again!');
}
} else {
if(Password == '') {
KnowsPassword = true;
}
console.log("Correct password!");
}
}
}
}, 2100);
The last console.log doesn't work. I've tried changing it a bunch of times, and none of them worked.
Your if-else statement for KnowsEmail == true is incorrect.
I've fixed incorrect statements and also removed unnecessary satements.
var KnowsUsername = true;
var KnowsEmail = true;
var KnowsPassword = true;
setTimeout(function () {
var Username = prompt('What is your username?');
if (Username == '') {
KnowsUsername = true;
console.log('Correct username!');
var Email = prompt('What is your E-mail?');
if (Email == '') {
KnowsEmail = true;
console.log('Correct E-mail!');
var Password = prompt('What is your password?');
if (Password == '') {
KnowsPassword = true;
console.log('Correct password!');
} else {
KnowsPassword = false;
console.error('\x1b[31m%s\x1b[0m', 'Aww! wrong password! try again!');
}
} else {
KnowsEmail = false;
console.error('\x1b[31m%s\x1b[0m', 'Wrong E-mail! try again!');
}
} else {
KnowsUsername = false;
console.error('\x1b[31m%s\x1b[0m', 'Aww! wrong username! try again!');
}
}, 2100);
Trying to make an address book for school and entered two fields and having validation. It seems like it's only validating the first field which is the name and ignoring the rest? I'm not sure if I have something wrong? It keeps displaying not a valid name as the error message and nothing else.
var validate_birthdate = my.isBirthdateBad(add_birthdate);
if (!valid_name.test(add_name)) {
alert("not a valid name");
valid_contact = false;
} else if (add_address.length > 0) {
if (!valid_address.test(add_address)) {
alert("not a valid address: " + add_address);
valid_contact = false;
}
} else if (add_birthdate.length > 0) {
if (!valid_birthdate.test(add_birthdate)) {
alert("not a valid birthdate");
valid_contact = false;
}
} else if (add_gender.length > 0) {
if (!valid_gender.test(add_gender)) {
alert("not a valid gender");
valid_contact = false;
}
} else if (add_ocupation.length > 0) {
if (!valid_occupation.test(add_occupation)) {
alert("not a valid job title");
valid_contact = false;
}
} else if (validate_birthdate) {
alert("not a valid birthdate: " + validate_birthdate);
valid_contact = false;
} else if (!(add_photo !== undefined) &&
(add_photo.length > 0) &&
(add_photo.indexOf("data:image/jpeg") === 0)) {
alert("image is not a jpeg!");
valid_contact = false;
}
// note the use of the "anonymous" function
// this returns an array of all of the matched contacts! Powerful!
var exists = _address_book_contacts.filter(function (contact) {
//check to see if the current "add_name"
// is found in the address book!
return contact.name() === add_name;
});
if (exists && (exists.length > 0)) {
if (!confirm("WARNING: " +
add_name +
" exists in database. " +
"Would you like to add again?")) {
valid_contact = false;
}
}
Code which give me error message but not clearing the error message after entering field :
var flag = 0;
function otpValidate() {
otp = oneTimePass.onetimepass.value;
if(otp == "") {
document.getElementById('error0').innerHTML = "Enter one time password";
flag = 1;
} else if(otp.length != 6) {
document.getElementById('error0').innerHTML = "PIN must be 6 digits";
flag = 1;
}
}
function check(form) {
flag = 0;
otpValidate();
if (flag == 1)
return false;
else
return true;
}
Just add an empty message in your main function. Then call a keyup function to call your main function. try something like:
function otpValidate() {
var otp = oneTimePass.onetimepass.value.trim();
if(otp == "") {
document.getElementById('error0').innerHTML = "Enter one time password";
flag = 1;
} else if(otp.length != 6) {
document.getElementById('error0').innerHTML = "PIN must be 6 digits";
flag = 1;
}
else {
document.getElementById('error0').innerHTML = "";
flag = 0;
}
}
var otp = oneTimePass.onetimepass;
otp.addEventListener("keyup", otpValidate);
Optimized way
function otpValidate() {
otp = oneTimePass.onetimepass.value.trim();
document.getElementById('error0').innerHTML = "";
flag = 0;
if(!otp) {
document.getElementById('error0').innerHTML = "Enter one time password";
flag = 1;
} else if(otp.length != 6) {
document.getElementById('error0').innerHTML = "PIN must be 6 digits";
flag = 1;
}
return flag;
}
function check(form) {
var flag = otpValidate();
if (flag == 1)
return false;
return true;
}
First of all fix the codes here
function check(form) {
//flag = 0; This will make no sense to check it
otpValidate();
if (flag == 1)
{
flag = 0;
return false;
}
else
return true;
}
And for the problem you are facing
function otpValidate() {
otp = oneTimePass.onetimepass.value;
if(otp == "") {
document.getElementById('error0').innerHTML = "Enter one time password";
flag = 1;
} else if(otp.length != 6) {
document.getElementById('error0').innerHTML = "PIN must be 6 digits";
flag = 1;
}
else {
document.getElementById('error0').innerHTML = "";
}
}
Try like this
var flag = 0;
function otpValidate() {
otp = oneTimePass.onetimepass.value;
if(otp == "") {
document.getElementById('error0').innerHTML = "Enter one time password";
flag = 1;
} else if(otp.length != 6) {
document.getElementById('error0').innerHTML = "PIN must be 6 digits";
flag = 1;
}
else {
document.getElementById('error0').innerHTML = "";
flag = 0;
}
}
function check(form) {
otpValidate();
if (flag == 1)
return false;
else
return true;
}
I have multiple required field controls on my aspx form.
Now what I want is to show the validation message on button click if anything is not filled or checked.
I want it on one message in JQuery.
Here is my JQuery code:-
$(document).ready(function () {
$('#btnSave').click(function (e) {
if (!validateTitle() || !validatePrefix() || !validateTextBoxes()) {
e.preventDefault();
}
});
function validateTitle() {
if ($("#ddlTitle").val() > "0") {
if ($("#ddlTitle").val() == "1104" && $("#txtTitle").val() === "") {
alert("Please enter the text in other title");
return false;
}
return true;
} else {
alert('Please select the title');
return false;
}
}
function validatePrefix() {
if ($("#ddlPrefix").val() > "0") {
if ($("#ddlPrefix").val() == "1110" && $("#txtPrefix").val() === "") {
alert("Please enter the text in other prefix");
return false;
}
return true;
} else {
alert('Please select the prefix');
return false;
}
}
function validateTextBoxes() {
if ($("#txtFirstName").val() === "") {
alert('First name is required');
return false;
}
if ($("#txtMiddleName").val() === "") {
alert('Middle name is required');
return false;
}
if ($("#txtLastName").val() === "") {
alert('Last name is required');
return false;
}
if ($("#txtFatherName").val() === "") {
alert('Father name is required');
return false;
}
if ($("#txtCurrentCompany").val() === "") {
alert('Current company is required');
return false;
}
if ($("#txtDateofJoin").val() === "") {
alert('Date is required');
return false;
}
if ($("#txtCurrentExp").val() === "") {
alert('Current Experience is required');
return false;
}
return true;
}
});
Try below code
var ErrArr = [];
$(document).ready(function () {
$('#btnSave').click(function (e) {
e.preventDefault();
validateTitle();
validatePrefix();
validateTextBoxes();
if(ErrArr.length > 0) {
alert(ErrArr.join("\n"));
ErrArr = [];
return false;
}
});
function validateTitle() {
if ($("#ddlTitle").val() > "0") {
if ($("#ddlTitle").val() == "1104" && $("#txtTitle").val() === "") {
ErrArr.push("Please enter the text in other title");
}
} else {
ErrArr.push('Please select the title');
}
}
function validatePrefix() {
if ($("#ddlPrefix").val() > "0") {
if ($("#ddlPrefix").val() == "1110" && $("#txtPrefix").val() === "") {
ErrArr.push("Please enter the text in other prefix");
}
} else {
ErrArr.push('Please select the prefix');
}
}
function validateTextBoxes() {
if ($("#txtFirstName").val() === "") {
ErrArr.push('First name is required');
}
if ($("#txtMiddleName").val() === "") {
ErrArr.push('Middle name is required');
}
if ($("#txtLastName").val() === "") {
ErrArr.push('Last name is required');
}
if ($("#txtFatherName").val() === "") {
ErrArr.push('Father name is required');
}
if ($("#txtCurrentCompany").val() === "") {
ErrArr.push('Current company is required');
}
if ($("#txtDateofJoin").val() === "") {
ErrArr.push('Date is required');
}
if ($("#txtCurrentExp").val() === "") {
ErrArr.push('Current Experience is required');
}
}
});
Instead of using alert all the time, save the message to a variable instead.
Then alert that message after all tests are done.
$(document).ready(function () {
var message = "";
$('#btnSave').click(function (e) {
message = "";
if (!validateTitle() || !validatePrefix() || !validateTextBoxes()) {
e.preventDefault();
alert(message);
}
});
function validateTitle() {
if ($("#ddlTitle").val() > "0") {
if ($("#ddlTitle").val() == "1104" && $("#txtTitle").val() === "") {
message += "Please enter the text in other title\n";
return false;
}
return true;
} else {
message += 'Please select the title\n';
return false;
}
}
....
});
Use the following fiddle [JSFiddle][1] , this will basically push all the error messages into an array and can show the results.
Please update if this works for you as i am not aware of markup
Just a simple trick you can do
just use a string variable for messages appending and counter.
$(document).ready(function () {
var Messages;
var counter=0;
$('#btnSave').click(function (e) {
validateTitle();
validatePrefix();
validateTextBoxes();
if(counter > 0)
{
alert(Messages);
e.preventDefault();
counter=0;
}
});
function validateTitle() {
debugger;
if ($("#ddlTitle").val() > "0") {
if ($("#ddlTitle").val() == "1104" && $("#txtTitle").val() === "") {
Messages += "Please enter the text in other title";
Messages += "\n";
counter ++;
}
} else {
Messages += 'Please select the title';
Messages += "\n";
counter ++;
}
}
function validatePrefix() {
debugger;
if ($("#ddlPrefix").val() > "0") {
if ($("#ddlPrefix").val() == "1110" && $("#txtPrefix").val() === "") {
Messages += "Please enter the text in other prefix";
Messages += "\n";
counter ++;
}
} else {
Messages += 'Please select the prefix';
Messages += "\n";
counter ++;
}
}
function validateTextBoxes() {
debugger;
if ($("#txtFirstName").val() === "") {
Messages += 'First name is required';
Messages += "\n";
counter ++;
}
if ($("#txtMiddleName").val() === "") {
Messages += 'Middle name is required';
Messages += "\n";
counter ++;
}
if ($("#txtLastName").val() === "") {
Messages += 'Last name is required';
Messages += "\n";
counter ++;
}
if ($("#txtFatherName").val() === "") {
Messages += 'Father name is required';
Messages += "\n";
counter ++;
}
if ($("#txtCurrentCompany").val() === "") {
Messages += 'Current company is required';
Messages += "\n";
counter ++;
}
if ($("#txtDateofJoin").val() === "") {
Messages += 'Date is required';
Messages += "\n";
counter ++;
}
if ($("#txtCurrentExp").val() === "") {
Messages += 'Current Experience is required';
Messages += "\n";
counter ++;
}
}
});
Just update counter and impliment check if check > 0 show message
(alert)
it will benefit you two things
User dont need to click each time and get alert.. dont need to
return false.user Must know at once what erors are in form.
Secondly code is simple/Simple logic.
Try this.
$(document).ready(function () {
var Errors = [];
$('#btnSave').click(function (e) {
if (!validateTitle() || !validatePrefix() || !validateTextBoxes()) {
if(Errors.length > 0) {
alert(Errors.join("\n"));
}
e.preventDefault();
}
});
function validateTitle() {
if ($("#ddlTitle").val() > "0") {
if ($("#ddlTitle").val() == "1104" && $("#txtTitle").val() === "") {
Errors.push("Please enter the text in other title");
}
return true;
} else {
Errors.push('Please select the title');
}
}
function validatePrefix() {
if ($("#ddlPrefix").val() > "0") {
if ($("#ddlPrefix").val() == "1110" && $("#txtPrefix").val() === "") {
Errors.push("Please enter the text in other prefix");
}
return true;
} else {
Errors.push('Please select the prefix');
}
}
function validateTextBoxes() {
if ($("#txtFirstName").val() === "") {
Errors.push('First name is required');
}
if ($("#txtMiddleName").val() === "") {
Errors.push('Middle name is required');
}
if ($("#txtLastName").val() === "") {
Errors.push('Last name is required');
}
if ($("#txtFatherName").val() === "") {
Errors.push('Father name is required');
}
if ($("#txtCurrentCompany").val() === "") {
Errors.push('Current company is required');
}
if ($("#txtDateofJoin").val() === "") {
Errors.push('Date is required');
}
if ($("#txtCurrentExp").val() === "") {
Errors.push('Current Experience is required');
}
return true;
}
});
Add perfect separation in each message to differentiate it.