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);
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;
}
I'm trying to get this code to work, but it's not working. I want to validate something with JavaScript
Code:
function validate() {
var letters = /^[A-Za-z]_$/;
u = document.getElementById("username").value;
if (validate.value.match(letters) {
return true;
} else {
alert("username is requiried");
return false;
}
}
return true;
}
Your code is not proper and also have lots of mistakes. I have corrected and implemented validations. Try the below code.
<script>
function validate() {
var u = document.getElementById("username").value;
var p = document.getElementById("password").value;
var letters = /^[A-Za-z]_$/;
if(u == '') {
alert("username is required");
return false;
}
if(!u.match(letters)) {
alert("username should be letters");
return false;
}
if(p == '') {
alert("password is required");
return false;
}
if(p.length < 6) {
alert("password length is too short");
return false;
}
return true;
}
</script>
Hope this will help
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 am having a hard time trying to do a correct form validation. I have Name, Email, and Phone Number fields. I implemented the validation check for all of them and when I click on the submit query, it returns email as false, but not anything else. It also will still submit the form. How do I fix this?
JSFiddle: http://jsfiddle.net/GVQpL/
JavaScript Code:
function validateForm(/*fullName, email, phoneNumber*/)
{
//-------------------------NAME VALIDATION-----------------------------//
var fullNameV = document.forms["queryForm"]["fullName"].value;
if (fullNameV == null || fullNameV == "")
{
alert("Name must be filled out!");
return false;
}
else if(fullNameV.indexOf(" ") <= fullNameV.length)
{
alert("Not a valid name");
return false;
}
//-------------------------EMAIL VALIDATION-----------------------------//
var emailV = document.forms["queryForm"]["email"].value;
if (emailV == null || emailV == "")
{
alert("Email must be filled out!");
return false;
}
var atpos = emailV.indexOf("#");
var dotpos = emailV.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length)
{
alert("Not a valid e-mail address");
return false;
}
//-------------------------PHONE # VALIDATION-----------------------------//
var phoneNumberV = document.forms["queryForm"]["phoneNumber"].value;
if (phoneNumberV == null || phoneNumberV == "")
{
alert("Phone Number must be filled out!");
return false;
}
var error = "";
var stripped = phoneNumberV.replace(/[\(\)\.\-\ ]/g, '');
if (phoneNumberV == "")
{
error = alert("You didn't enter a phone number.\n");
phoneNumberV.style.background = 'Yellow';
}
else if (isNaN(parseInt(stripped)))
{
error = alert("The phone number contains illegal characters.\n");
phoneNumberV.style.background = 'Yellow';
}
else if (!(stripped.length == 10))
{
error = alert("The phone number is the wrong length. Make sure you included an area code.\n");
phoneNumberV.style.background = 'Yellow';
}
return error;
}
Update your fiddle's html for the function to be called onsubmit="return validateForm()" and removed the required="required" changed your function to work, you can see it here:
http://jsfiddle.net/GVQpL/3/
function validateForm(/*fullName, email, phoneNumber*/)
{
//-------------------------NAME VALIDATION-----------------------------//
var fullNameV = document.forms["queryForm"]["fullName"].value;
if (fullNameV == null || fullNameV == "")
{
alert("Name must be filled out!");
document.forms["queryForm"]["fullName"].focus();
return false;
}
else if(fullNameV.indexOf(" ") >= fullNameV.length)
{
alert("Not a valid name");
document.forms["queryForm"]["fullName"].focus();
return false;
}
//-------------------------EMAIL VALIDATION-----------------------------//
var emailV = document.forms["queryForm"]["email"].value;
if (emailV == null || emailV == "")
{
alert("Email must be filled out!");
document.forms["queryForm"]["email"].focus();
return false;
}
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(emailV)){
alert("Not a valid e-mail address");
document.forms["queryForm"]["email"].focus();
return false;
}
//-------------------------PHONE # VALIDATION-----------------------------//
var phoneNumberV = document.forms["queryForm"]["phoneNumber"].value;
if (phoneNumberV == null || phoneNumberV == "")
{
alert("Phone Number must be filled out!");
document.forms["queryForm"]["phoneNumber"].focus();
return false;
}
var error = "";
var stripped = phoneNumberV.replace(/[\(\)\.\-\ ]/g, '');
if (phoneNumberV == "")
{
alert("You didn't enter a phone number.\n");
document.forms["queryForm"]["phoneNumber"].focus()
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
else if (isNaN(parseInt(stripped)))
{
alert("The phone number contains illegal characters.\n");
document.forms["queryForm"]["phoneNumber"].focus();
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
else if (!(stripped.length == 10))
{
alert("The phone number is the wrong length. Make sure you included an area code.\n");
document.forms["queryForm"]["phoneNumber"].focus();
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
if(!confirm('Are you sure you want to submit your DSLR query?')){
return false;
}
return true;
}
I have two two date fields - from date and to date, and i need to validate 3 things
Both the values are entered or not
Date datatype check
To date must be greater than from date.
But my script is not working.
can some body please check?
Thanks
function checkBothDates(sender,args)
{
var from = document.getElementById(sender.From);
var to = document.getElementById(sender.To);
var behaviorId = sender.behavior;
var from_value = from.value;
var to_value = to.value;
if((from_value == "")&&(to_value == ""))
{
args.IsValid = true;
}
else
{
if((from_value != "")&&(to_value != ""))
{
if((isValidDate(from_value))&&(isValidDate(to_value)))
{
if(from_value < to_value)
{
args.IsValid = false;
sender.errormessage = "To date must be greater than or equal to the from date";
}
}
else
{
args.IsValid = false;
sender.errormessage = "Please enter valid dates in both the fields";
if(behaviorId != null)
{
openCollapsiblePanel(behaviorId);
}
}
}
else
{
args.IsValid = false;
sender.errormessage = "Please make sure you enter both the values";
if(behaviorId != null)
{
openCollapsiblePanel(behaviorId);
}
}
}
}
function isValidDate(val)
{
var format = 'dd/MM/yyyy'
var regexp = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if (!regexp.test(val))
{
return false;
}
else
{
try
{
$.datepicker.parseDate(format,val,null);
return true;
}
catch(Error)
{
return false;
}
}
}
Your code is pretty repetitive, you can shorten a lot of it.
Also note that the regex check is entirely unnecessary, since $.datepicker.parseDate() won't accept anything invalid anyway.
function checkBothDates(sender, args) {
var from = parseDate( $(sender.From).val() ),
to = parseDate( $(sender.To).val() );
args.IsValid = false;
if (from == "" && to == "" || from && to && from <= to) {
args.IsValid = true;
} else if (from == null || to == null) {
sender.errormessage = "Please enter valid dates in both the fields";
} else if (from > to) {
sender.errormessage = "To date must be greater than or equal to the from date";
} else {
sender.errormessage = "Please make sure you enter both the values";
}
if (!args.IsValid && sender.behavior) {
openCollapsiblePanel(sender.behavior);
}
}
function parseDate(val) {
if (val == "") return "";
try {
return $.datepicker.parseDate('dd/MM/yyyy', val);
} catch (ex) {
return null;
}
}
There is a problem in your code aroun the 19th line. You wrote:
if(from_value < to_value) {
args.IsValid = false;
sender.errormessage = "To date must be greater than or equal to the from date";
}
But you definitely want that from_value is smaller then to_value. Fix it!