Issues in add validate email in javascript - javascript

Here is my code:
<form method="post" name="form1" action="invitation_enrollv5.asp?action=1" onSubmit="return GetTextValue()">
<input style="float:right;" id="nextbutton" name="" type="submit" value="Next" />
</form>
May i know, how and where can i add validate script to validate input email address.
If i blank or invalid id means it shows error states.
Can anyone help me? thanks in advance.

For input boxes, you can specify the type as email, and the browser will validate for you.
<input type="email" required>
Or for javascript:
function validate(emailString) {
return /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(emailString)
}
This will return true if the value for the emailString parameter is a valid email.

Lets assume you have an input field in your HTML as such -
<form name="emailForm">
<input type="email" id="email" name="email" />
</form>
In your javascript you can then add an event handler whenever a user activates
the text field and then clicks elsewhere (or uses tab to navigate to the next field)
$('#email').blur(function() {
// Instead of .blur() you can also just have the
// form submit event use the checkEmail() function.
checkEmail();
});
function checkEmail(){
var email = document.forms["emailForm"]["email"].value;
var atnum = email.replace(/[^#]/g, '').length
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || email.length <= dotpos + 2 || atnum > 1) {
// E-mail was not valid
$('#email').css({border: '1px solid #e74c3c'});
alert("Not a valid e-mail address");
setTimeout( function() {
$('#email').css({border: '1px solid #555'});
}, 800);
} else {
// E-mail was OK
alert("You're good to go!");
}
}
Here's a fiddle

Related

Post a form after javascript check

I would like to send a form after javascript validation in validateLengths() function.
If I fill a form action the form is send anyway if I don't specify javascript:void(0)
Here is my code so far...
Currently I'm just able to alert "submit form".
Sorry, I'm a noob in javascript.
Thank you for any related information.
Have a nice day.
Nicolas.
function validateLengths() {
let fnameCap = document.getElementById("firstName").value;
let lnameCap = document.getElementById("lastName").value;
if (fnameCap.length < 4 ) {
alert("First name must be atleast 4 characters. ");
return false;
}
if (lnameCap.length < 6) {
alert("Last name must be atleast 6 characters. ");
return false;
}
if(fnameCap.length >= 4 && lnameCap.length >= 6){
alert ("submit form"); // don't know how to send form here
}
}
function capitalize(){
let first = document.getElementById("firstName");
let last = document.getElementById("lastName");
let fcapitalized = first.value.toUpperCase();
let lcapitalized = last.value.toUpperCase();
first.value = (fcapitalized);
last.value = (lcapitalized);
validateLengths();
}
<form action="javascript:void(0)" id="theForm" title="form1">
<input name="firstName" type="text" id="firstName" value="At least 4 chars">
<br>
<input name="lastName" type="text" id="lastName" value="At least 6 chars">
<br>
<input type="submit" name="submit" id="submit" value="Submit" onClick="javascript:capitalize()">
</form>

Two actions in one form

I have a form and i need to use to actions in it .
one for getting informations entered in the fields and redirect the user to another page and the other one for checking the email validation .
the email validation is for the first fields ,the other field is normal
here's my code :
<form name="myform" class="login" action="getinfo.php" method="POST">
<input name="f1" type="text" placeholder="email" autofocus/>
<input name="f2" type="password" placeholder="example2"/>
this is the js code for checking the first field for the email :
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;
}
i have no idea how to use two actions in one form
Thanks in advance, hope I have been concise and precise enough.
To achieve what you want while keeping it as close to what you had, you can do:
function validateForm() {
var x = document.forms["myform"]["f1"].value; //changed to "myform" and "f1"
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;
}
}
<!--onsubmit handler added to <form> -->
<form name="myform" class="login" action="getinfo.php" method="POST" onsubmit="return validateForm()">
<input name="f1" type="text" placeholder="email" autofocus/>
<input name="f2" type="password" placeholder="example2"/>
<input type="submit"> <!--submit button was missing -->
</form>
Note that the important part is the submit handler that runs when you submit the form and returns true if you want the form to be submitted or false otherwise, which you were missing.
It's also important to validate on the server side as well, otherwise any user may disable javascript and bypass the validation.
As a side note, changing the type of the email input to email already forces validation by the browser, which is easier.

Getting JavaScript validation to work with PHP

<?php
if (isset($_POST['submit']) ) {
//send to database
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function validateForm() {
var usernameentry = document.forms["registrationform"]["username2"].value;
var passwordentry = document.forms["registrationform"]["password2"].value;
var nameentry = document.forms["registrationform"]["password2"].value;
var emailentry = document.forms["registrationform"]["email"].value;
var atpos = emailentry.indexOf("#");
var dotpos = emailentry.lastIndexOf(".");
if (usernameentry.length < 3 || username.length > 20){
alert("Username must be inbetween 4 and 20 characters");
return false;
}
else if (passwordentry.length < 3 || password.length > 20){
alert("Password must be inbetween 4 and 20 characters");
return false;
}
else if (nameentry.length < 3 || name.length > 45){
alert("Name must be inbetween 4 and 45 characters");
return false;
}
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=emailentry.length || emailentry.length > 154) {
alert("Not a valid e-mail address");
return false;
}
else
{
return true;
}
}
</script>
</head>
<body>
<form name="registrationform" method="post" action="login.php" onsubmit="return validateForm();">
Name: <input type="text" name="name"/>
<br/>
<br/>
Email: <input type="text" name="email"/>
<br/>
<br/>
Username: <input type="text" name="username2"/>
<br/>
<br/>
Password: <input type="password" name="password2"/>
<br/>
<br/>
<input type = "submit" name = "submit" value = "submit" />
<br/>
<br/>
</form>
</body>
I want the contents of the if statement to run ONLY when the form has been validated with JavaScript, it runs regardless of whether the value returns is true or false.
I'm guessing what I need to do is similar to
if (isset($_POST['submit']) && onsubmit == true)
Obviously that's not right, but I don't know how to do it.
I know validating with php is a much more logical approach, but I need to demonstrate use of JavaScript.
You don't need to do that. When the form is validated, it will be sent to login.php
You can see this question HTML/Javascript: Simple form validation on submit
Also, there are a lot of libraries which could help you
http://www.javascript-coder.com/html-form/javascript-form-validation.phtml

Why is return false not keeping my form from submitting?

http://jsfiddle.net/1z9Lr5rv/1/
I am creating a contact form for my website. I thought it was working fine, but it always submits the form, wether or not there's an error, where return false should keep the form from submitting.
I'm sorry if this is really obvious and dumb, but I'm very new to this sort of thing . . .
The form works fine if you take it out of JS Fiddle (you should post the code here anyway). Here it is (with the redundant parts removed):
<div class="body">If you have any questions about me, my teaching or curriculum, etc., please don't hesitate to contact me here. Please fill out all the fields in this form..
<br>
<br>
<form name="contact-me" class="contact-me" onsubmit="return warnsub(this)"
method="POST"
action="https://secure.mailjol.net/allforms/u/3dcdda44.php" autocomplete="off">
First Name: <input type="text" name="fname">
Last Name: <input type="text" name="lname">
Email Address: <input type="text" name="email">
Message: <textarea name="message" id="message"></textarea>
<input type="submit" value="Send">
</form>
</div>
<script>
function warnsub(form) {
var error = [];
var fname = form.fname;
var lname = form.lname;
var email = form.email;
var message = form.message;
var atpos = email.value.indexOf("#");
var dotpos = email.value.lastIndexOf(".");
if (fname.value == "") {
error.push(fname);
}
if (lname.value == "") {
error.push(lname);
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
error.push(email);
}
if (message.value == "") {
error.push(message);
}
if (error.length) {
for (i = 0; i < error.length; i++) {
// You want to clear this class if the user has another
// attempt and gets it right
error[i].className = 'error';
}
error[0].focus();
return false;
}
return true;
}
You need to handle the event object that is automatically passed into the submit handler and call preventDefault().
Example:
var myForm = document.forms["contact-me"];
myForm.onsubmit = function(e)
{
if(!warnsub())
{
e.preventDefault();
}
}
As #Pointy has commented: IE9 does not automatically pass the event object to the onsubmit delegate. Discussion of how to shiv this is outside the scope of this question.
But just a side note - its good to try and avoid function calls in inline html (e.g. <form onsubmit=//your function() /> calls. Your Google-Fu can teach you why.

Form submission - confirmation

I am currently using the dotmailer to generate a new form (simple textbox and submit button) that automatically adds the email address to the dotmailer address book.
When someone submits an email address - they can be taken to a webpage.
<input type="hidden" name="ReturnURL" id="returnValueHidden" value="URL">
I have been trying to work out a way to present an alert box saying "submitted" and not take take the user to a thank you page.
Solution?
document.getElementById('returnValueHidden').value = alert("Email successfully submitted.");
But all this does, it displays an alert box and then redirects to the following url (even when the value is inserted or not).
http://dmtrk.net/undefined?result=success
404 The page you are looking for could not be found
Is there anyway i can adjust this so it submits the email but does not redirect.
Full Code:
<script language="javascript">
<!--
function validate_signup(frm) {
var emailAddress = frm.Email.value;
var errorString = '';
if (emailAddress == '' || emailAddress.indexOf('#') == -1) {
errorString = 'Please enter your email address';
}
var els = frm.getElementsByTagName('input');
for (var i = 0; i < els.length; i++)
{
if (els[i].className == 'text' || els[i].className == 'date' || els[i].className == 'number')
{
if (els[i].value == '')
errorString = 'Please complete all required fields.';
}
else if (els[i].className == 'radio')
{
var toCheck = document.getElementsByName(els[i].name);
var radioChecked = false;
for (var j = 0; j < toCheck.length; j++)
{
if (toCheck[j].name == els[i].name && toCheck[j].checked)
radioChecked = true;
}
if (!radioChecked)
errorString = 'Please complete all required fields.';
}
}
document.getElementById('returnValueHidden').value = alert("Email successfully submitted.");
var isError = false;
if (errorString.length > 0)
isError = true;
if (isError)
alert(errorString);
return !isError;
}
//-->
</script>
HTML:
<form name="signup" id="signup" action="http://dmtrk.net/signup.ashx" method="post" onsubmit="return validate_signup(this)">
<input type="hidden" name="addressbookid" value="">
<input type="hidden" name="userid" value="41929">
<input type="hidden" name="ReturnURL" id="returnValueHidden" value="URL">
<input type="text" name="Email" onfocus="if(this.value=='Email')this.value='';" class="blueTextBox">
<input type="Submit" name="Submit" class="submit">
</form>
To send information without doing a full page reload you need to use AJAX. It's easiest to use an existing javascript library, for example jQuery.
Check out these pages:
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/on/

Categories

Resources