send email after validation - javascript

hi i am new enough to JavaScript and am wonder how to send details in email after validation ,heres my code
<script type="text/javascript">
var compName=false;
var compContry=false;
var compsub=false;
var compphone=false;
var compemail=false;
function validate_form(form)
{
if(compName)
{
document.getElementById('country').focus();
compName=true;
if(compContry)
{
document.getElementById('subject').focus();
compContry=true;
if(compsub)
{
document.getElementById('Phone').focus();
compsub=true;
if(compphone)
{
document.getElementById('email').focus();
compphone=true;
if(compemail)
{
//I just use alert to show it works.
alert("Your Details Are Sent ");
compemail=true;
}
else
{
document.getElementById('email').focus();
compemail=false;
}
}
else
{
document.getElementById('Phone').focus();
compphone=false;
}
}
else
{
document.getElementById('subject').focus();
compsub=false;
}
}
else
{
document.getElementById('country').focus();
compContry=false;
}
}
else
{
document.getElementById('username').focus();
compName=false;
}
}

You need some kind of server-side scripting to send emails.

After it passes validation you can submit your form like this
document.formname.submit();
in your case, this goes at the end of your function
if (comP... == true) {
form.submit();
}

you can add return false; after each validation if you are using cutom js
for example
var first_name = $("#first_name");
if(!$.trim(first_name.val()).length) {
first_name.closest('.form-group').removeClass('has-success').addClass('has-error');
return false;
}else{
first_name.closest('.form-group').removeClass('has-error').addClass('has-success');
}
return false will stop the submit button to proceed until the form is not filled.
freelancer

Related

how to pass username and password from page to another using javascript

please i want to know how to store the user input data in the registeration page then i pass it to login page and in login page i validate if the user write the right username and password or not(that already passed from registeration page)
here is my js code for registeration page:
<head>
<script>
//function to check if the passoword is matched
function checkpass() {
if (document.getElementById('psw').value ==
document.getElementById('psw-confirm').value) {
document.getElementById('message').style.color = 'green';
document.getElementById('message').innerHTML = 'Matched Passowrds';
} else {
document.getElementById('message').style.color = 'red';
document.getElementById('message').innerHTML = 'Those passwords didn’t match. Try again.';
}
}
//function to disable the submit button if the password is not matched
function check_pass() {
if (document.getElementById('psw').value ==
document.getElementById('psw-confirm').value) {
document.getElementById('submit').disabled = false;
} else {
document.getElementById('submit').disabled = true;
}
}
//function of cancel button
function goBack() {
window.history.back();
}
//function to only choose one gendre
function onlyOne(checkbox) {
var checkboxes = document.getElementsByName('check')
checkboxes.forEach((item) => {
if (item !== checkbox) item.checked = false
})
}
</script>
<link href="RegisterartinStyle.css" rel="stylesheet">
</head>
You can use sessionStorage to store temporary data like this...
sessionStorage.setItem('Username',username);
sessionStorage.setItem('Password',password);
To retreive the data from any of your pages...
var Username = sessionStorage.getItem('Username');
var Password = sessionStorage.getItem('Password');
Blow everything away...
sessionStorage.clear();

validating custom domain for signup form using javascript?

I am trying to validate my company email-id's in sign up form...so that the form accepts only my company mail id...so now whats the problem here is after validating(ie; when we click submit button then we get an alert message) the form is getting refreshed and the entered values are cleared...so any help or suggestions so that it is not refreshed??thanks in advance...
My Javascript method is:
function submitAlbum() {
var frm = document.getElementById("frmRegistration");
//validateEmail(document.getElementById('email').value);
var email = document.getElementById('email').value;
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
if (re.test(email)) {
if (email.indexOf('#bdisys.com', email.length - '#bdisys.com'.length) !== -1) {
// alert('Submission was successful.');
var r = confirm("Are You Sure You Want to add your details.");
if (r == true) {
frm.action = "signUpServlet?formidentity=doRegistration&checkboxStatus=" + checkboxStatus;
frm.submit();
}
}
else {
document.getElementById('email').focus();
alert('Email must be a Company e-mail address (your.name#bdisys.com).');
return false;
}
}
else {
document.getElementById('email').focus();
alert('Not a valid e-mail address.');
return false;
}
}
I think this will do the job.
<input type = "email" pattern ="^[a-z0-9._%+-]+#bdisys.com">
Check this bin
http://jsbin.com/dew/5/edit
You should bind your validation method to the submit event of your form.
Inside the validation method, stop the event to propagate if the field is invalid, or let it bubble if it's ok.
var frm = document.getElementById("frmRegistration");
frm.addEventListener('submit', validate, false);
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
function validate(event) {
// validateEmail
var email = document.getElementById('email').value;
var confirmed = false;
if (re.test(email)) {
confirmed = true;
if (email.indexOf('#bdisys.com', email.length - '#bdisys.com'.length) !== -1) {
confirmed = confirm("Are You Sure You Want to add your details.");
}
} else {
document.getElementById('email').focus();
alert('Email must be a Company e-mail address (your.name#bdisys.com).');
}
if (!confirmed) {
event.preventDefault();
event.stopPropagation();
return false;
}
}
I suggest you to use jQuery to make your code simplier and before all portable.

Form click function to check variable before submitting

I am using a $.get function to check the connection to the server before submitting the ASP login form. If the get function is successful and returns a true then the form should submit, otherwise if it fails and returns false, it should not.
I have tried many different configurations, but everything I've tried has either rendered the button inoperable, or only showing a true, and never a false!
Any advice is appreciated. Thanks.
<asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Enter" ValidationGroup="LoginUserValidationGroup" class="submitButton" />
UPDATE - The code below executes the get function correctly, but I have a feeling the problem lies within $('form').submit();
When true is returned the page refreshes like it sent the data, but the system does not log the user in. Why is this!?
submitButton.click(function () { // capitalize username on login
var url = 'https://examplesite.com/';
$.get(url).done(function () {
if (usernameBox.val() === '') {
usernameBox.attr('placeholder', 'Username Required');
passwordBox.attr('placeholder', '');
usernameBox.focus();
return false;
}
else if (passwordBox.length && passwordBox.val() === '') {
passwordBox.attr('placeholder', 'Password Required');
usernameBox.attr('placeholder', '');
passwordBox.focus();
return false;
}
else if (passwordBox.length && passwordBox.val().length < 6) {
passwordBox.focus();
return false;
}
else {
alert('Successful - Now logging in');
$('form').submit();
}
}).fail(function () {
alert('Failed - No Connection');
});
return false;
});
};
$.get is an async function, so online is never set to what you think it is since the rest of the code is being processed before the call is complete. Move your logic into the .done part of it!
$.get(url).done(function () {
online = true;
if (online == true) {
alert('Success');
$('form').submit();
}
else if (online == false) {
alert('Cannot Connect');
return false;
}
else {
return false;
}
}).fail(function () {
online = false;
});

A little help please with a contact form validator script

I have this email form validation script:
<script type="text/javascript" language="javascript">
function validateForm(thisform){
if(thisform.Name.value=="") {
alert("Ooouuupppsss... You did not enter your Name.");
thisform.Name.focus();
return false;
}
if(thisform.Email.value=="") {
alert("Ooouuupppsss... You did not enter a valid Email Address.");
thisform.Email.focus();
return false;
}
if(thisform.Subject.value=="") {
alert("Ooouuupppsss... You did not enter your Subject.");
thisform.Subject.focus();
return false;
}
if(thisform.Message.value=="") {
alert("Ooouuupppsss... You did not enter your Message.");
thisform.Message.focus();
return false;
}
}</script>
Can someone please tell me what do I have to add in this script in order to make the users enter a valid email address. Also I would like in the rest of the fields to make users to enter text (not links).
I've tried to add different pieces of code which I found on different websites but they did not work and this is because I am not sure if I am adding them right.
Thank you for reading my request.
All the best,
Andi
For e-mail checking you can use following code in else part after checking if e-mail is empty
function validateForm(){
var email = document.getElementById("email").value;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (email.search(emailRegEx) == -1) {
alert("e-mail is not valid");
return false;
}
}
and for url with same logic you can use following regular expression
var urlRegEx = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)/;
following is a working example based on your work, you can improve this code it is only for showing you how it should be.
function validateForm(thisform){
if(thisform.Name.value=="") {
alert("Ooouuupppsss... You did not enter your Name.");
thisform.Name.focus();
return false;
}
else{
var name = thisform.Name.value;
if (!checkURL(name)) {
alert("name cannot be a url");
return false;
}
}
if(thisform.Email.value=="") {
alert("Ooouuupppsss... You did not enter a valid Email Address.");
thisform.Email.focus();
return false;
}
else{
var email = thisform.Email.value;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (email.search(emailRegEx) == -1) {
alert("e-mail is not valid");
return false;
}
}
if(thisform.Subject.value=="") {
alert("Ooouuupppsss... You did not enter your Subject.");
thisform.Subject.focus();
return false;
}
else{
if (!checkURL(thisform.Subject.value)) {
alert("subject cannot contain a url");
return false;
}
}
if(thisform.Message.value=="") {
alert("Ooouuupppsss... You did not enter your Message.");
thisform.Message.focus();
return false;
}
else{
if (!checkURL(thisform.Message.value)) {
alert("message cannot contain a url");
return false;
}
}
}
function checkURL(url){
var urlRegEx = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)/;
if (url.search(urlRegEx) == -1) {
return true;
}
return false;
}
See this post for regex urls: regular expression for url
See this post for email validation: Validate email address in JavaScript?
See this for X browser event listening, if would use jQuery, ie8 uses attach see this: Javascript add events cross-browser function implementation: use attachEvent/addEventListener vs inline events
I would recommend looping through the form inputs, and checking if its email and if its not run the regex against the link.
(function(){
var validateForm = function(form){
var errors = [], inputs = form.getElementsByTagName('input');
for(var input = 0; input<inputs.length; input++){
var currentInput = inputs[input];
if(currentInput.value === ''){
// handle attributes here for error message, push error message
if(currentInput.attribute('name') === 'email'){
// handle email
// push error message
}
}
}
return errors;
}
var contactForm = document.getElementById('contact');
contactForm.addEventListener('submit', function(e){
var errorMessages = validateForm(contactForm);
if(errorMessages.length === 0){
} else {
e.preventDefault() // stop the form from submitting
// handle your messages
}
}
}());

Why does my form still submit when my javascript function returns false?

Here is my Javascript formvalidator function:
function companyName() {
var companyName = document.forms["SRinfo"]["companyName"].value;
if (companyName == ""){
return false;
} else {
return true;
}
}
function companyAdd() {
var companyAdd1 = document.forms["SRinfo"]["companyAdd1"].value;
if (companyAdd1 == ""){
return false;
} else {
return true;
}
}
function companyCity() {
var companyCity = document.forms["SRinfo"]["companyCity"].value;
if (companyCity == ""){
return false;
} else {
return true;
}
}
function companyZip() {
var companyZip = document.forms["SRinfo"]["companyZip"].value;
if (companyZip == ""){
return false;
} else {
return true;
}
}
function enteredByName() {
var enteredByName = document.forms["SRinfo"]["enteredByName"].value;
if (enteredByName == ""){
return false;
} else {
return true;
}
}
function dayPhArea() {
var dayPhArea = document.forms["SRinfo"]["dayPhArea"].value;
if (dayPhArea == ""){
return false;
}
}
function dayPhPre() {
var dayPhPre = document.forms["SRinfo"]["dayPhPre"].value;
if (dayPhPre == ""){
return false;
} else {
return true;
}
}
function dayPhSub() {
var dayPhSub = document.forms["SRinfo"]["dayPhSub"].value;
if (companyAdd1 == ""){
return false;
} else {
return true;
}
}
function validateForm() {
if (companyName() && companyAdd() && companyCity() && companyZip() && enteredByName() && dayPhArea() && dayPhPre() && dayPhSub()) {
return true;
} else {
window.alert("Please make sure that all required fields are completed.");
document.getElementByID("companyName").className = "reqInvalid";
companyName.focus();
return false;
}
}
Here are all of my includes, just in case one conflicts with another (I am using jquery for their toggle()):
<script type="text/javascript" src="formvalidator.js"></script>
<script type="text/javascript" src="autoTab.js"></script>
<?php
require_once('mobile_device_detect.php');
include_once('../db/serviceDBconnector.php');
$mobile = mobile_device_detect();
if ($mobile) {
header("Location: ../mobile/service/index.php");
if ($_GET['promo']) {
header("Location: ../mobile/service/index.php?promo=".$_GET['promo']);
}
}
?>
<script src="http://code.jquery.com/jquery-1.7.1.js"></script>
Here is my form tag with the function returned onSubmit:
<form method="POST" action="index.php" name="SRinfo" onsubmit="return validateForm();">
The validation works perfectly, I tested all fields and I keep getting the appropriate alert, however after the alert the form is submitted into mysql and sent as an email. Here is the code where I submit my POST data.
if($_SERVER['REQUEST_METHOD']=='POST') {
// Here I submit to Mysql database and email form submission using php mail()
It would seem to me that this line is likely blowing up:
companyName.focus();
The only definition I see for companyName is the function. You can't call focus on a function.
This blows up so the return false is never reached.
I would comment out all the code in the validation section and simply return false. If this stops the form from posting then there is an error in the actual code performing the validation. Add each part one at a time until the error is found.
My guess is the same as James suggests that you are calling focus on the function 'companyName'. The line above this seems to be trying to get the element from the document with the same name but you are not assigning this to a variable so that you can call focus on it.

Categories

Resources