I have the following sequence on a form page, first it runs through the captcha then it validates the email address and then asks if you are sure you want to unsubscribe.
Everything works perfectly except that clicking "Cancel" still submits the form. I can't use "onclick" in the submit button because it will bypass the captcha code. In my "if the email is true 'else'" statement I've tried both "return" and "return:false" but neither of them stop the form submission.
Thanks for your help.
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' name="unsubscribe" method='post' onsubmit="return checkForm(this);"">
function checkForm(form) {
var frm = document.unsubscribe;
if(!form.captcha.value.match(/^\d{5}$/)) {
alert('Please enter the CAPTCHA digits in the box provided');
form.captcha.focus();
return false;
}
if (validEmail(frm.Email.value) != true) {
alert("Please enter a valid email address");
frm.Email.focus();
return false;
}
if (validEmail(frm.Email.value) == true) {
confirm('Are you sure you want to unsubscribe?');
return true;
}
else {
return false;
}
}
function validEmail(email){
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (email.search(emailRegEx) == -1) {
status = false;
}
else {
status = true;
}
return status;
}
confirm returns a boolean - true if the user clicked "Ok", false if they clicked "Cancel", so simply return the result of the confirm call:
if (validEmail(frm.Email.value) == true) {
return confirm('Are you sure you want to unsubscribe?');
}
Related
After I submit the form, the form will ignore the onsubmit whether the return is true or false, the form will directly go to form action.
I want to validate the input, if it is null it will remain on the same page and pop up an alert.
This is my JavaScript
<script>
function validLogin() {
if (document.login.username.value == "") {
alert("Please enter Login Name.");
document.loginform.userName.focus();
return false;
}
if (document.login.password.value == "") {
alert("Please enter password.");
document.userform.password.focus();
return false;
}
alert("Welcome User");
return true;
}
</script>
This is my form
<form action="Login" method="post" name="login" onsubmit="return validLogin();">
The userName field is miscased in the code
<script>
function validLogin() {
if (document.login.username.value == "") {
alert("Please enter Login Name.");
document.login.username.focus();//Here
return false;
}
if (document.login.password.value == "") {
alert("Please enter password.");
document.login.password.focus();
return false;
}
alert("Welcome User");
return true;
}
</script>
I'm not able to redirect to a single page using windows location in .js page.
However I checked with alert box to see whether the condition is passing true or not and it is working while location is not working.
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email == "test1#gmail.com" && password == "test1") {
alert("Login successfully");
window.location.href = 'messages.php';
return false;
} else {
attempt--; // Decrementing by one.
alert("You have left " + attempt + " attempt;");
// Disabling fields after 3 attempts.
if (attempt == 0) {
document.getElementById("email").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}
I feel I'm missing something.
I suspect you're calling validate like this:
<form onsubmit="validate()" ...>
That won't use the return value of validate to cancel the submit. You need a return:
<form onsubmit="return validate()" ...>
Since the submission is not being cancelled, the form submission is a navigation action, which overrides your assignment to window.location.href.
In a comment you've said you're doing this:
<button type="submit" name="submit" onclick="validate()" class="btn-secondary">Sign In</button>
If so, adding the return to the onclick should fix it on any modern browser:
<button type="submit" name="submit" onclick="return validate()" class="btn-secondary">Sign In</button>
But I would move it to an onsubmit on the form instead.
Side note: There's no need for the type="submit" on that button. submit is the default type for button elements.
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email == "test1#gmail.com" && password == "test1") {
alert("Login successfully");
window.location.href = 'messages.php';
return false;
} else {
attempt--; // Decrementing by one.
alert("You have left " + attempt + " attempt;");
// Disabling fields after 3 attempts.
if (attempt == 0) {
document.getElementById("email").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
}
return false; // ALWAYS return this. else it will proceed with page submit.
}
}
//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/
I am making simple auth form with some messages for user while he is typing the username/email in the input. Before form submission code works just fine, but after I submit the form (with preventDefault) this 'input-checker' stops working. Can anyone tell me why and how to make it work?:-)
var reValidEmail = /^[^\s#]+#[^\s#]+\.[^\s#]+$/;
$("#auth-input").on('input', function () {
if (document.getElementById("auth-input").value.indexOf("#") + 1) {
if (!reValidEmail.test(document.getElementById("auth-input").value)) {
$("#login-comment").text("Please enter valid email");
} else {
$("#login-comment").text("");
}
}
});
$("#log-in-form").submit(function (e) {
e.preventDefault();
if ( document.getElementById("auth-input").value.length > 0
&& ( document.getElementById("auth-input").value.indexOf("#") == -1
|| ( document.getElementById("auth-input").value.indexOf("#") + 1
&& reValidEmail.test(document.getElementById("auth-input").value)
)
)
) {
//some ajax request
} else {
if (document.getElementById("auth-input").value.indexOf("#") + 1) {
$("#login-comment").text("Please enter valid email"); //does not hide after form submission and input change for correct one
} else {
$("#login-comment").text("Please enter username or email"); //does not hide after form submission and input change for correct one
}
}
});
When I combine my php form validation code with my javascript validation code, the javascript code fails to work when I hit the submit button. It will only validate the first form field and not the 3 others and then php will validate all fields. I don't want the php form validation to do anything until javascript has completed the form validation.
When I use only php or only javascript to validate, then the code works correctly. What am I missing here? Is it something to do with the beginning of the form?
"form name="contactform" id="contactform" method="post"
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"
onsubmit="return validateentry();">"
Am I supposed to do the php form validation while "action" goes to a different web page?
The javascript code:
function validateemail()
{
var emailentry=document.forms.contactform.email.value;
at=emailentry.indexOf("#");
period=emailentry.lastIndexOf(".");
if(at < 1 || ( period - at < 2 ))
{
alert("Please enter correct email in the format of 'yourmail#yourwebsite.com'")
document.forms.contactform.email.focus();
return false;
}
return(true);
}
function validatephonenumber()
{
var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/;
var numbers = document.forms.contactform.phone.value;
var verified = re.exec(numbers);
if (!verified)
{
alert("Please enter a phone number in the format of 999-999-9999");
return false;
}
return(true);
}
function validateentry()
{
if(document.forms.contactform.name.value=="")
{
alert("Please provide your name.");
document.forms.contactform.name.focus();
return false;
}
if(document.forms.contactform.company.value=="")
{
alert("Please provide your company name. If you don't have one, simply state
that you don't.");
document.forms.contactform.company.focus();
return false;
}
if(document.forms.contactform.email.value == "")
{
alert("Please provide an Email address.");
document.forms.contactform.email.focus();
return false;
}else{
var validformat=validateemail();
if(validformat==false)
{
return false;
}}
if(document.forms.contactform.phone.value=="")
{
alert("Please provide a phone number in the format 999-999-9999.");
document.forms.contactform.phone.focus();
return false;
}
else if(document.forms.contactform.phone.value.length < 12)
{
alert("Please provide the phone number in the format of 999-999-9999.");
document.forms.contactform.phone.focus();
return false;
}
else
{
var validnumber=validatephonenumber();
if(validnumber==false)
{
return false;
}}
if(document.forms.contactform.msg.value=="")
{
alert("Please provide a message.");
document.forms.contactform.msg.focus();
return false;
}
return(true);
}
It's unclear without more code but based on your comment I am going to guess that you have incorrectly written your php and it's breaking your javascript/html code. Perhaps one of your quotes? Look at the source code of the page and run it through one of the online validation services such as http://validator.w3.org and http://www.jslint.com
Try this:
PHP HTML:
<?php
echo "<form name='contactform' id='contactform' method='post'
action='' onsubmit='return validateentry(this);'>"
...
Validation JavaScript:
function validateemail(e)
{
var emailentry = e.value
, at = emailentry.indexOf("#")
, period = emailentry.lastIndexOf(".");
if(at < 1 || ( period - at < 2 ))
{
alert("Please enter correct email in the format of 'yourmail#yourwebsite.com'")
e.focus();
return false;
}
return true;
}
function validatephonenumber(e)
{
var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/
, numbers = e.value;
if (!re.exec(numbers))
{
alert("Please enter a phone number in the format of 999-999-9999");
e.focus();
return false;
}
return true;
}
function validateentry(f)
{
if(f.name.value == "")
{
alert("Please provide your name.");
f.name.focus();
return false;
}
if(f.company.value == "")
{
alert("Please provide your company name. If you don't have one, simply state
that you don't.");
f.company.focus();
return false;
}
if(f.email.value == "")
{
alert("Please provide an Email address.");
f.email.focus();
return false;
}
else
{
var validformat = validateemail(f.email);
if(validformat == false)
{
return false;
}
}
if(f.phone.value == "" || f.phone.value.length < 12 || (validnumber = validatephonenumber(f.phone)) == false)
{
alert("Please provide the phone number in the format of 999-999-9999.");
f.phone.focus();
return false;
}
if(f.msg.value == "")
{
alert("Please provide a message.");
f.msg.focus();
return false;
}
return true;
}