Submitting a PHP form with onClick - javascript

So I currently have a download link and an input field for an email address on my website.
In order to download the file you first need to put in your email.
I use a form to do this, with the email field being an input field and the download button being a submit button.
I like HTML5's form validation (the required fields, field types etc, it all looks very nice).
The problem is that if I use onClick in my submit button then none of the nice form validation works.
<form>
<input type="email" id="email" placeholder="Please enter email" required>
<input type="submit" class="btn" onclick="downloadWin()" value="Windows">
<input type="submit" class="btn" onclick="downloadOsx()" value="Osx">
</form>
<script>
function downloadWin(){
event.preventDefault();
var email = $("#email").val();
if(email != ''){
if(validateEmail(email)){
location.href='http://s/index.php?page=downloadWin&email='+email;
}
}
}
function downloadOsx(){
event.preventDefault();
var email = $("#email").val();
if(email != ''){
if(validateEmail(email)){
location.href='http://s/index.php?page=downloadOsx&email='+email;
}
}
}
</script>
This might not be the cleanest way to do it, so please if you think you know a better way tell me :)

Try this:
<form onsubmit="download(this.email.value,this.system.value)" id="form">
<input type="email" id="email" name="email" placeholder="Please enter email" required>
<input type="radio" name="system" value="Win" required >Windows
<input type="radio" name="system" value="Osx" >Osx
<input type="submit" class="btn" value="Download">
</form>
<script type="text/javascript">
document.getElementById("form").addEventListener("submit", function(event){
event.preventDefault();
});
function download(email_value,sys_value){
location.href='http://s/index.php?page=download'+sys_value+'&email='+email_value;
}
</script>
Result:

try this code
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function downloadWin() {
var email = $("#email").val();
if (email != '') {
if (validateEmail(email)) {
location.href = 'http://s/index.php?page=downloadWin&email=' + email;
}
}
return false;
}
function downloadOsx() {
var email = $("#email").val();
if (email != '') {
if (validateEmail(email)) {
location.href = 'http://s/index.php?page=downloadOsx&email=' + email;
}
}
return false;
}

Below is the working code snippet (without using HTML5 validation). You can run and test it. I have used the jquery with jquery.validate plugin. You can uncomment the commented code to redirect user to the target url. Let us know if this what you are looking for or not. Feel free to comment if there is anything that you feel confusing.
$(document).ready(function(){
$(".btn-download").on("click", function(e) {
e.preventDefault();
e.stopImmediatePropagation();
if ($("#validateForm").valid()) {
var name = $(this).val();
var email = $("#email").val();
if (name === "Windows") {
//location.href = 'http://s/index.php?page=downloadWin&email=' + email;
console.log('http://s/index.php?page=downloadWin&email=' + email);
}
if (name === "Osx") {
console.log('http://s/index.php?page=downloadOsx&email=' + email);
//location.href = 'http://s/index.php?page=downloadOsx&email=' + email;
}
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.js"></script>
<form method="post" action="" id="validateForm" novalidate>
<input type="email" id="email" placeholder="Please enter email" required>
<input type="submit" name="btnSubmit" class="btn btn-download" value="Windows">
<input type="submit" name="btnSubmit" class="btn btn-download" value="Osx">
</form>

Related

validate email and display accordingly

I want to check the email validity in Javascript and then show alert box if its invalid and if valid then show the div2. But its not working
Here is javascript:
function _(x){
return document.getElementById(x);
}
function Phase1()
{
myemail = _("email").value;
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (reg.test(designeremail) == false)
{
alert('Invalid Email Address');
}
else
{
_("phase1").style.display = "none";
_("phase2").style.display = "block";
}
}
Here is my html:
<form id="myform" onsubmit="return false" >
<div id="phase1">
<label>Email</label><div><input type="text" id="email" name="email" required></div>
<div><button onclick="Phase1()" class="btn"><strong>Next</strong></button></div>
</div>
<div id="phase2">
<label>Name</label><div><input type="text" id="mname" name="myname" required></div>
<div><button onclick="Phase2()" class="btn"><strong>Submit</strong></button></div>
</div>
</form>
but even with wronng email it proceeds and shows the phase2
I think this is js and not php. Btw, it's because probably you're testing on the wrong variable:
if (reg.test(designeremail) == false)
you're testing designeremail, which is different from email from the form which probably you wanted test against to.

Submitting form even when validation regex is wrong

i am having this problem when i submit the form where both the password and username is wrong. I get an alert box saying that i have enter the wrong details. But when the username is correct and password is validation is wrong it will give me an arlet box by when pressed ok it will submit the form even when i have returned false.
Help please much appreciated
<script type="text/javascript">
function validate(form_id, firstName, password){
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = document.forms[form_id].elements[firstName].value;
var password = document.forms[form_id].elements[password].value;
if (Reg.test(username) == false) {
alert('Invalid Username.');
document.forms[form_id].elements[firstName].focus();
return false;
}
if (Reg1.test(password) == false) {
alert('Invalid Password.');
document.forms[form_id].elements[password].focus();
return false;
}
}
</script>
<form id="form_id" action="userlogininput.cgi" onsubmit="javascript:return validate('form_id','firstName','password');" name="form" method="post">
Username : <input type="text" id="firstName" name="firstName" class="textboxH-300" required><br>
Password : <input type="password" id="password" name="password" class="textboxH-300" required><br><br>
<input id="submitbtn" type="submit" value="Submit"/>
</form>
You can use e.preventDefault() to prevent form sending.
Here is a code example
(function(){
function validate(e) {
e.preventDefault(); // prevent the form sending
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = document.getElementById('firstName');
var password = document.getElementById('password');
if (Reg.test(username.value) == false) {
alert('Invalid Username.');
username.focus();
return false;
}
if (Reg1.test(password.value) == false) {
alert('Invalid Password.');
password.focus();
return false;
}
}
//add event listener for form submission
document.getElementById('form_id').addEventListener('submit',validate);
})();
<form id="form_id" action="userlogininput.cgi" name="form" method="post">
Username :
<input type="text" id="firstName" name="firstName" class="textboxH-300" required>
<br> Password :
<input type="password" id="password" name="password" class="textboxH-300" required>
<br>
<br>
<input id="submitbtn" type="submit" value="Submit" />
</form>
Try prevent default event.
Bind function to the form submit event:
function validate(form){
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = form.querySelector('[name=firstName]');
var password = form.querySelector('[name=password]');
if (Reg.test(username.value) == false) {
event.preventDefault();
alert('Invalid Username.');
username.focus();
return false;
}
if (Reg1.test(password.value) == false) {
event.preventDefault();
alert('Invalid Password.');
password.focus();
return false;
}
}
<form onsubmit="validate(this)">
<input name="firstName">
<br>
<input name="password">
<br>
<button type="submit">submit</submit>
</form>

Validate email field in the form while adding to the list

I am adding users to the list using pure js and I am trying to validate the email field using ajax. How to validate the email field before submitting the form? If the email field is valid then i want to submit or else I have show the error in valid email.
Here is the code
<form id="myform">
<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name">
<input id="email" type="text" name="email" placeholder="email">
<button onclick='return addUser();' type="submit">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
function addUser(){
var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(username + ' ' + email));
list.appendChild(entry);
return false;
}
if you using js then below code will definitely help you.
if (document.getElementById('email').value != '')
{
reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(document.getElementById('email').value) == true) {
}
else {
alert("Please Enter Valid Email Id");
return false;
}
}
else{
alert("Please Enter Email Id");
return false;
}
edited code: u have to just replaced it with your code, hope will work for you:
function addUser(){
var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email').value;
var entry = document.createElement('li');
if (email.value != '')
{
reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(email.value) == true) {
entry.appendChild(document.createTextNode(username + ' ' + email));
list.appendChild(entry);
return false;
}
else {
alert("Please Enter Valid Email Id");
return false;
}
}
else{
alert("Please Enter Email Id");
return false;
}
}
Try This
HTML
<form id="myform">
<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name">
<input id="email" type="email" name="email" placeholder="email">
<button onclick='return addUser();' type="submit">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
JS
function addUser(){
var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email').value;
var entry = document.createElement('li');
var emailPat = /^(\".*\"|[A-Za-z]\w*)#(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/
var EmailmatchArray = email.match(emailPat);
if (EmailmatchArray == null) {
email.focus(); }
else {
entry.appendChild(document.createTextNode(username + ' ' + email));
list.appendChild(entry);
}
return false;
}
DEMO HERE
Try this
It will validate the field , then add the info to list
<form id="myform" onsubmit="return addUser();">
<h2>Add a User:</h2>
<input id="username" type="text" required name="username" placeholder="name">
<input id="email" type="email" required name="email" placeholder="email">
<button type="submit">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
DEMO
For the simple validation use the following way (type="email")
<input id="email" type="email" name="email" placeholder="email">
Here is the w3schools link http://www.w3schools.com/js/tryit.asp?filename=tryjs_form_validate_email
For Depth use this :
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
//Your Code here
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</form>
Try this
function addUser() {
var email = document.getElementById('email').value;
var username =document.getElementById('username').value;
$.post('/url/to/validation/email/from/db', { "email": email, "username": username }, function(data) {
if(data && data.Success){
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(username + ' ' + email));
document.getElementById('users').appendChild(entry);
}else{
alert('Email already exists!');
}
},'json');
return false;
}
This will validate the entered email against server and then adds to the list.

Form wont submit after correct email validation jquery

So my form throws up the correct error when no email is given. But when a correct email is put into the field, it wont submit. Where am I going wrong here? Thanks for any advice and help!
var myEmailRegEx = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
$(document).ready(function(){
$("#submitbutton").click(function(e){
var none_answered = true;
var eMailToTest = $('#email').val();
if(!myEmailRegEx.test(eMailToTest)) {
e.preventDefault();
none_answered = true;
$('#email').addClass('error');
$('#texthere').html("Please provide a correct email");
}
else {
$('#email').removeClass('error');
return true;
}
});
});
<style type="text/css">
.error
{
color:red;
}
#texthere
{
color:red;
}
</style>
<body>
<form>
<label id="email" class="req"><span>*</span>Email:</label>
<input id="email" class="req" name="email" value="" type="email"></br>
<div id="texthere"></div>
<input id="submitbutton" type="submit" value="submit" formaction="http://www.utah.edu/">
</form>
</body>
You have duplicate IDs, for the label and input field. Because of that the value of eMailToTest was always blank.
<label for="email" class="req"><span>*</span>Email:</label>
Demo: Fiddle
Try to do like this:
$("#submitbutton").click(function (e) {
e.preventDefault();
var none_answered = true;
var eMailToTest = $('#email').val();
if (!myEmailRegEx.test(eMailToTest)) {
none_answered = true;
$('#email').addClass('error');
$('#texthere').html("Please provide a correct email");
} else {
$('#email').removeClass('error');
$('form').submit();
}
});
Also, seem like your none_answered variable is redundant here.
Try this change id of label
<form action="http://www.utah.edu/">
<label class="req"><span>*</span>Email:</label> // Here duplicate id removed
<input id="email" class="req" name="email" value="" type="email">
</br>
<div id="texthere"></div>
<input id="submitbutton" type="submit" value="submit" />
</form>
Script
var myEmailRegEx = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
$("#submitbutton").click(function(e){
e.preventDefault();
var none_answered = true;
var eMailToTest = $('#email').val();
if(!eMailToTest.match(myEmailRegEx)) {
none_answered = true;
$('#email').addClass('error');
$('#texthere').html("Please provide a correct email");
console.log('if')
}
else {
console.log('else')
$('#email').removeClass('error');
$(this).closest('form').submit();
}
});
DEMO
You did a few mistakes.
Use event submit on forms (not click event)
You used id attribute on label and email. ID can be used only once on page.
var eMailToTest = $('#email').val();
It returned value of first element with ID email. So it's label (which has no value). You want input element instead.
Here is the working code.
HTML:
<form>
<label for="email" class="req"><span>*</span>Email:</label>
<input id="email" class="req" name="email" value="" type="text"><br>
<div id="texthere"></div>
<input id="submitbutton" type="submit" value="submit" formaction="http://www.utah.edu/">
</form>
Javascript:
var myEmailRegEx = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
(function(){
$("form").on('submit', function(e){
var eMailToTest = $('#email').val();
if(!myEmailRegEx.test(eMailToTest)) {
e.preventDefault();
$('#email').addClass('error');
$('#texthere').html("Please provide a correct email");
} else {
$('#email').removeClass('error');
}
});
})();
Also none_answered variable is redundant here.
Working example.
Hope this helps :)

JavaScript not validating form on second submit request

I have JavaScript code that will validate a form on the first submit request, but if the user then hits submit again, even though they have not rectified the form errors, the form will not process the validation function and will just submit.
I would like the validation function to be executed every time the user clicks on the submit button.
Thanks for any help, code below.
Martin
<form action="site.url" method="post" name="signup" onsubmit="return validateForm()">
<label for="firstname"><span id="inactiveErrorFname">Please enter your first name<br></span>
First name <strong title="Required" class="required">*</strong></label><br>
<input type="text" name="firstName">
<label for="surname"><br><span id="inactiveErrorSname">Please enter your Surname<br></span>
Surname</label><input type="text" name="lastName">
<label for="email">
<span id="inactiveErrorEmail"><br>Please enter your Email address<br></span>
Email address <strong title="Required" class="required">*</strong></label>
<input type="text" name="emailAddress">
<input class="button" type="submit" value="Sign up" />
</form>
<script>
function validateForm()
{
var x=document.forms["signup"]["firstName"].value;
var y=document.forms["signup"]["lastName"].value;
var z=document.forms["signup"]["emailAddress"].value;
var atpos=z.indexOf("#");
var fname;
var sname;
var email;
/* Validate first name */
if (x==null || x=="")
{
document.getElementById("inactiveErrorFname").id = "activeErrorFname";
fname = "true";
}
/* Validate Surname */
if (y==null || y=="")
{
document.getElementById("inactiveErrorSname").id = "activeErrorSname";
sname = "true";
}
/* Validate email */
if (atpos<1)
{
document.getElementById("inactiveErrorEmail").id = "activeErrorEmail";
email = "true";
}
if (fname=="true" || sname=="true" || email =="true")
{
return false;
}
}
</script>
The problem you are facing is created by the fact you are changing the id's of certain elements. The first time you run your code, these statements are succesfully runned:
document.getElementById("inactiveErrorFname").id = "activeErrorFname";
document.getElementById("inactiveErrorSname").id = "activeErrorSname";
document.getElementById("inactiveErrorEmail").id = "activeErroremail";
The second time however the id's of these elements have changed, resulting in the fact that these statements call upon unexisting elements. This results in a javascript fatal error, with as consequence no return false. The second time your form will thus be submitted as it normally is. The solution to this problem is not changing the id's but changing the class of the error-labels. You can find an example in this fiddle.
HTML:
<form action="#" method="post" name="signup" onsubmit="return validateForm()">
<label for="firstname">
<span class="inactive" id="errorFname">Please enter your first name<br></span>
First name <strong title="Required" class="required">*</strong>
</label><br>
<input type="text" name="firstName"><br><br>
<label for="surname">
<span class="inactive" id="errorSname">Please enter your Surname<br></span>
Surname
</label><br>
<input type="text" name="lastName"><br><br>
<label for="email">
<span class="inactive" id="errorEmail"><br>Please enter your Email address<br></span>
Email address <strong title="Required" class="required">*</strong>
</label><br>
<input type="text" name="emailAddress"><br><br>
<input class="button" type="submit" value="Sign up" />
</form>
Javascript:
function validateForm()
{
var x=document.forms["signup"]["firstName"].value;
var y=document.forms["signup"]["lastName"].value;
var z=document.forms["signup"]["emailAddress"].value;
var atpos=z.indexOf("#");
var fname;
var sname;
var email;
/* Validate first name */
if (x==null || x=="")
{
document.getElementById("errorFname").className = "active";
fname = "true";
}
/* Validate Surname */
if (y==null || y=="")
{
document.getElementById("errorSname").className = "active";
sname = "true";
}
/* Validate email */
if (atpos<1)
{
document.getElementById("errorEmail").className = "active";
email = "true";
}
if (fname=="true" || sname=="true" || email =="true")
{
return false;
}
return false;
}

Categories