Why won't JavaScript alert box work in this example? - javascript

I am trying to validate 3 fields in a html form using javascript. If any of the fields are empty an alert box appears with a message indicating which fields are empty. This all works fine. I'm having a problem getting the message (msg2) to appear in an alert box when the form has been completed properly. My code is below-I know it's just something simple that I'm missing if anyone can help. Thanks!
var valid = true;
var msg="Incomplete form:\n";
var msg2="Success! There are no null fields.";
if ( myname== "" ) {
msg+="You need to fill the name field!\n";
valid = false;
}
if ( emailaddress == "" ) {
msg+="You need to fill in your email!\n";
valid = false;
}
if ( commentString == "" ) {
msg+="You need to fill in your comment!\n";
valid = false;
}
if ((!myname=="")&&(!emailaddress=="")&&(!commentString=="")){
return msg2;
}
if (!valid) alert(msg);
return valid;
}

You're right, it's something simple: return msg2; will not open an alert box. You still have to call alert() somewhere.

i think a little change in your code will solve the problem:
if (!valid) alert(msg);
return valid;
}
change it to
if (!valid) {
alert(msg);
return valid;
}

if (!valid) {
alert(msg);
} else {
alert(msg2);
}
return valid
Maybe somethign like that? And remove the block with if ((!myname=="")&& ...

Related

Cant Access Window.location.replace after IF ELSE in JAVASCRIPT

I try to replace my page , but it cant still replace.
i think that error from after IF and ELSE after i loged from console
but still cant resolve that.
help..
function LoginWithEmail(){
var email = curEmail.indexOf(emailLogin.value);
var password = curPass.indexOf(passLogin.value);
if(emailLogin.value === curEmail[email] && passLogin.value === curPass[password]){
return window.location.replace("admin-dashboard.php");
}else{
alert("Your email or password are empty or wrong!");
return false;
}
}

I am trying to use use this validation in my html tag by using onsubmit=return validateForm()

//this is the javascript program for validation
function validateForm()
{
var name=document.myform.uname.value;
var password=document.myform.password.value;
var conpass = document.myform.repassword.value;
boolean valid = true;
if(password != conpass)
{
alert("password is not same");
valid=false;
}
else if(name==null || name=="")
{
alert("User Name should not be blank..");
valid=false;
}
else if(password==""|| password==null)
{
alert("Password should not be blank");
valid=false;
}
else if(!this.form.checkbox.checked)
{
alert('You must agree to the terms first.');
return false;
}
else{
return valid;
}
};
//and this is the html in which I am using this but it is not working properly,it is not taking the js validation and directly forwarding me to the reg.jsp page.
<form action="reg.jsp" name="myform" method="post" onsubmit="return validateForm()" >
In order to prevent submit via javascript, you have to return false in your onsubmit handler.
So the in the following line the validateForm() must return false:
<form action="reg.jsp" name="myform" method="post" onsubmit="return validateForm()" >
You have many if-else blocks that set the var valid = false and this is ok.
But this valid variable should be returned. You do this only in the last else blocks.
else if(!this.form.checkbox.checked)
{
alert('You must agree to the terms first.');
return false;
}
else{
return valid;
}
The previous checks are just preparing the variable, but don't return it.
And this is what you need to do.
Here is an example how it can be done:
function validateForm() {
var name=document.myform.uname.value;
var password=document.myform.password.value;
var conpass = document.myform.repassword.value;
var valid = true;
var message = "everything is valid";
if(password != conpass)
{
message = "password is not same";
valid = false;
}
else if(name==null || name=="")
{
message = "User Name should not be blank..";
valid = false;
}
else if(password==""|| password==null)
{
message = "Password should not be blank";
valid = false;
}
else if(!this.form.checkbox.checked)
{
message = "You must agree to the terms first.";
valid = false;
}
alert(message);
return valid;
};
Other improvement could be:
Reordering the conditions by descending importance.
For example: if the Term are not accepted, is not important, if the password is empty.
If password is empty, it is not important, if the conpass is the same.
Using html5, which hast more input types and adjustable build-in validation for common cases. See more here: http://html5doctor.com/html5-forms-input-types/

ELSE IF Statement not validating information

Validate form has been working fine but I have now tried adding email validation to the code and now nothing will validate, form submits without any popup error boxes.
Here's The Current Code:
<script type="text/javascript">
function validateForm(){
var a=document.forms["order_form"]["fname"].value;
var b=document.forms["order_form"]["address"].value;
var c=document.forms["order_form"]["city"].value;
var d=document.forms["order_form"]["pcode"].value;
var e=document.forms["order_form"]["email"].value;
var atpos=email.indexOf("#").value;
var dotpos=email.lastIndexOf(".").value;
if (a==null || a=="")
{
alert("Full name must be filled out");
return false;
}
else if (b==null || b=="")
{
alert("Address must be filled out");
return false;
}
else if (c==null || c=="")
{
alert("City must be filled out");
return false;
}
else if (d==null || d=="")
{
alert("Post-Code must be filled out");
return false;
}
else if (e==null || e=="")
{
alert("Email Address must be filled out");
return false;
}
else if (atpos<1||dotpos<atpos+2||dotpos+2>=email.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
Form is likely submitting due to the following errors
Change:
var atpos=email.indexOf("#").value;
var dotpos=email.lastIndexOf(".").value;
To
var atpos=e.indexOf("#");
var dotpos=e.lastIndexOf(".");
indexOf() returns a number not an object so there is no value property.
Also as noticed by #fpierrat email should be e
I don't see any declaration for email before following:
var atpos=email.indexOf("#").value;
var dotpos=email.lastIndexOf(".").value;
Maybe you meant e, not email?
Also delete the .value after indexof() calls, see #charlieftl's answer, we were quite complementary on this ;-)

JavaScript not giving alert on invalid Confirm Password text

For proper registration, user is required to enter password two times and password in both these textboxes should match.
However, on validating this using this code, JavaScript is not showing alert dialog.
Here pswrd and pswrd1 are two textboxes of password type.
var message="";
var result=false;
if(pswrd.value!== pswrd1.value)
{
message+="\nPasswords did not match";
result=false;
}
if(!result)
{
alert(message);
}
Try this
var message="";
var result=false;
if(pswrd.value!== pswrd1.value)
{
message = "Passwords did not match";
result=false;
}
else {
result = true;
}
if(!result)
{
alert(message);
}
Try this code.
if(pswrd.value!== pswrd1.value)
{
alert("Password does not matched!");
return false;
}
Hope this help :)
if(pswrd.value !== pswrd1.value)
the text in bold above should be != and not !==
!== is not an operator, use == for equality and != for unequality

javascript problems when another javascript added

I have the following script that works fine until I add the other javascript below...
First Script in the header tags
function validateForm() {
var valid = true;
var errMsg = "";
var email = document.emailform.email.value;
var filter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if(email.length <= 0) {
valid = false;
errMsg += "Email address is required.\n";
} else {
if (!filter.test(email)) {
valid = false;
errMsg += "Please provide a valid email address.\n";
}
}
if (errMsg.length > 0) {
alert(errMsg);
return false;
}
}
and just before the closing tags I have...
$('#form').submit(validateForm);
The above works fine, except once I add the script below, validateForm no longer works. This following is added just before the closing body tags.
cbr202=Math.random()*10000000000000000;document.write('<scr'+'ipt language="JavaScript" src="http://example.com/landing.php?lpip=411&202cb='+cbr202+'" type="text/javascript"></scr' + 'ipt>');
I can't seem to figure out what's causing the issue. Hoping someone with experience can see the problem.
Solved: I figured it out... it was due to my own sloppiness. I should have the jquery event handler below the document.write script, not above it.
You forgot to add a closing } to the function. That caused an error and resulted in any JS coming after that to not execute.
function validateForm() {
var valid = true;
var errMsg = "";
var email = document.emailform.email.value;
var filter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if(email.length <= 0) {
valid = false;
errMsg += "Email address is required.\n";
} else {
if (!filter.test(email)) {
valid = false;
errMsg += "Please provide a valid email address.\n";
}
}
if (errMsg.length > 0) {
alert(errMsg);
return false;
}
}
the url generated by
src="http://mysite.com/landing.php?lpip=411&202cb='+cbr202
does not exist. The browser tries to load the script from the url using a get request and fails.
cbr202=Math.random()*10000000000000000;
I think you need change code same below
var cbr202=Math.random()*10000000000000000;

Categories