Can anyone tell my why this email validation is not working? - javascript

I am trying to get an email validation to work and can't seem to figure out the problem. I want it to alert if what is entered is not a valid email. The code I attached is the email function and the form code for the email. Help is appreciated thanks!
{
var emailfield=document.getElementById("emailaddress").value;
var atpos=emailfield.indexOf("#");
var dotpos=emailfield.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=emailfield.length){
alert("Please enter a valid email address with an # and proper domain.")
return false;
}
}
Here is the code for the form.
<form action='#' method='post' name='f1' id="VPN" onsubmit='return checkButons(this)'>
Aspects <br>
<input type='radio' name='aspect' id='aspect1' value='security' />Security <br>
<input type='radio' name='aspect' id='aspect2'value='speed' /> Speed<br>
Features:<br>
<input type='checkbox' name='feat1' id='feat1'value='highspeedvpn' /> High Speed VPN <br>
<input type='checkbox' name='feat2' id='feat2' value='transactionguard' />Transaction Guard <br>
<input type='checkbox' name='feat3' id='feat3'value='antivirus' /> Antivirus Addon <br>
<h3 id="generaltext">Fill out your information below:</h3>
<p>
Name:<input name="Name"id='name'size=:50 type="text" required><br>
</p>
<p>
Email Address:<input name="Emailaddress"id='emailaddress'size=:50 type="text" required><br>
</p>
<p>
Street Address:<input name="S_Address"id='s_address'size=:50 type="text" required><br></p>
<p>
Address 2:<input name="Address_2"id='address_2'size=:50 type="text" required><br></p>
<p>
Zip Code:<input name="Zip"id='zip'size=:50 type="text" required><br>
<p>
City:<input name="City"id='city'size=:50 type="text" required><br>

You can use validation with regular exp -
var email = text_email.value;
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,}))$/;
if (re.test(email)) {
alert("Error msg");
return false;
}

Please see following. You can move validation logic to a different function.
JavaScript:
function checkButons(element) {
...
var emailfield = document.getElementById("emailaddress").value;
var atpos = emailfield.indexOf("#");
var dotpos = emailfield.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= emailfield.length) {
alert("Please enter a valid email address with an # and proper domain.")
return false;
}
...
}
HTML:
<form action='#' method='post' name='f1' id="VPN" onsubmit='return checkButons(this)'>
....
<p>
Email Address:<input name="Emailaddress"id='emailaddress'size=:50 type="text" required><br>
</p>
....
</form>

Instead of using <input name="Emailaddress"id='emailaddress'size=:50 type="text" required> use type email, the browser will do the validations for you,but if you want to extra valdiate in server side you could use RegExp for it

Hi check this codepen https://codepen.io/anon/pen/BeeZBv?editors=1111
It is your JS code and it appears to be working, it may not be catching all possible conditions, but it is definitely working. Can you let me know what is not working?
Here is code
<input name="Emailaddress"id='emailaddress'size=:50 type="text" required>
<button onclick="validate()">Click me</button>
function validate() {
var emailfield=document.getElementById("emailaddress").value;
var atpos=emailfield.indexOf("#");
var dotpos=emailfield.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=emailfield.length){
console.log("Please enter a valid email address with an # and proper domain.")
return false;
}
}

Please keep a submit button on form,as I validated code form is not submitting once you having more input in a form and calling form event onSubmit and form is submitting with one field.
Function checkButons() {
var emailfield = document.getElementById("emailaddress").value;
var atpos = emailfield.indexOf("#");
var dotpos = emailfield.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= emailfield.length) {
alert("Please enter a valid email address with an # and proper domain.")
return false;
}
}
HTML Code :
<form action='#' method='post' name='f1' id="VPN" onsubmit="checkButons()">
Email Address:<input name="Emailaddress"id='emailaddress'size=:50 type="text" required>
Street Address:<input name="S_Address"id='s_address'size=:50 type="text" required>
<input type="submit" value="Submit">
</form>

Related

Checking if the input fields are filled in properly (pure javascript)

I almost complete the form validation, but the only pain in the ass for me is:
1) Input fields should be checked themselves when some have filled in the input field and click outside the input box.
2) when someone leaves all the input fields empty and clicked on the send button.
Anyone an idea how I can fixed that?
function validateForm() {
var name = document.getElementById("name");
var email = document.getElementById("email");
var nameValidation = document.getElementById("nameValidation");
var emailValidation = document.getElementById("emailValidation");
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (name.value.length == "") {
nameValidation.innerHTML = " Please fill in your name";
name.focus();
} else {
nameValidation.innerHTML = " Right";
}
if(!filter.test(email.value) || (email.value.length == "")) {
emailValidation.innerHTML = " Please enter a valid email address";
email.focus();
}
else {
emailValidation.innerHTML = " Right!";
}
}
<form action="#" id="form" method="post" name="form">
<img id="close" src=IMAGE/close.png alt="close-button" onclick="div_hide()"/>
<h3><b>Application form</b></h3>
<input id="name" class="application" name="name" placeholder="Name" type="text" maxlength="30" /><span id="nameValidation"></span><br/>
><input id="email" class="application" placeholder="Email" type="text" maxlength="254" /><span id="emailValidation"></span>
<div id="upload-box">
<input id="upload" class="application upload" type="file"/>
<input id="submit" class="application apply-button" type="button" onclick="validateForm()" value="Send"/>
</div>
</form
<input type="email" required />
Job done.

Failed to validate email address with regular expression

I would like to run my page to test out whether my validation works. However, it does not work with email address. I have added regular expression for email address. It doesn't validate fully.
I entered a#live without typing .com it able to accept it. I assume this is because i type input="email" Correct me wrong. Is it due to the wrong regular expression or maybe the way I placed my code?
javascript
function validate(){
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var email = document.getElementById('email').value;
var emailReg = '/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/';
var re = /^[\w ]+$/;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(email=="")
{
alert('Please fill in email fields');
return false;
}
else if(fname=="")
{
alert('Please fill in first name fields');
return false;
}
else if(lname=="")
{
alert('Please fill in last name fields');
return false;
}
return true;
}
register.php
<form name="registrationForm" method="post" id="registrationForm" class="registrationForm" action="processRegister.php" onclick="validate">
<div class='input1'>
<span id="emailAddress-label" class="help"></span>
<input class="regemailaddr" id="emailAddress" name="emailAddress" type="email" placeholder="Email Address " value="" required>
</div>
<br>
<span id="fname-label" style="margin-bottom:" class="help"></span>
<input id="fname" name="fname" type="text" placeholder="First Name " class="fname" value="" required>
<span id="lname-label" class="help"></span> <input id="lname" name="lname" type="text" placeholder="Last Name " class="lname" value="<?php echo $user_profile["lname"]; ?>" required>
<br>
<button class="greybtn" type="submit" id="submitButton">Submit</button>
<button class="cancelbtn" type="button" id="cancelButton" onclick="window.location='#';return false;">Cancel</button>
</form>
You have defined a regular expression
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
but you do not test against it
var isEmail = emailReg.test(email);

Validation fails when multiple <form> tags are present in the same HTML document

I have multiple form tags in my html doc and want to validate them. However the validation function won't give any result. Tried
adding name field to the <form> the validation() does not return any result.
When I use validation with only one <form> the result is correct.
here are the two form tags:
<div id="pinfo">
<form>
<fieldset>
<legend>Personal Information</legend>
Name:
<input type="text" name="name" value="Enter name">
<br><br>
Email:
<input type="email" name="eamil" value="Enter email id">
<br><br>
Confirm email id:
<input type="text" name="cemail" value="">
<br><br>
Password:
<input type="password" name="pass" value="">
<br><br>
Confirm password:
<input type="password" name="cpass" value="">
<br><br>
</fieldset>
</form>
</div>
<div id="linfo">
<form>
<fieldset>
<legend>Location and Contact</legend>
Location:
State:
<!more code ahead>
<script>
function validateForm() {
var eid = document.forms["loginform"]["emailid"].value;
if (eid == null || eid == "") {
alert("Email id must be entered.");
return false;
}
var pwd = document.forms["loginform"]["password"].value;
if (pwd == null || pwd == ""){
alert("Please enter the password.");
return false;
}
var p = document.forms["locinfo"]["pno"].value;
if (p == null || p=="") {
alert("Please enter the phone no.");
return false;
}
</script>
Validating Form Fields Using JavaScript in FrontPage
There are some mistakes in your code.
You have not given form name as "loginform" which you are using in validation function.
And second thing you missed is "onsubmit" attribute on form element
Here is working code for you
function validateForm() {
console.log(document.forms["loginform"])
var eid = document.forms["loginform"]["eamil"].value;
if (eid == null || eid == "") {
alert("Email id must be entered.");
return false;
}
var pwd = document.forms["loginform"]["pass"].value;
if (pwd == null || pwd == "") {
alert("Please enter the password.");
return false;
}
/*var p = document.forms["locinfo"]["pno"].value;
if (p == null || p == "") {
alert("Please enter the phone no.");
return false;
}*/
}
<div id="pinfo">
<form method="post" name="loginform" action="/" onsubmit="return validateForm()">
<fieldset>
<legend>Personal Information</legend>
Name:
<input type="text" name="name" value="">
<br><br>
Email:
<input type="email" name="eamil" value="">
<br><br>
Confirm email id:
<input type="text" name="cemail" value="">
<br><br>
Password:
<input type="password" name="pass" value="">
<br><br>
Confirm password:
<input type="password" name="cpass" value="">
<br><br>
<input type="submit" name="submit" />
</fieldset>
</form>
</div>

html5 form not working properly

I have a search form on every page of my website which works perfectly, when submitting the form it goes to a page called search.php..
I have the same form also on my contact page where i also have a contact form.
the contact form does not have a submit button because i use ajax to send the post variables to a contact_process.php page. The contact form is working perfectly however on this page the search form does not work.. When I press the submit button on the search form it just refreshes the whole contact page instead of going to the search.php page. can anyone help? thanks.
The javascript and ajax for contact form:
document.getElementById('submit_message').addEventListener('click', sendMessage, false);
function sendMessage(){
$('#submit_message').removeClass("point_finger_animation");
$('#pointing_finger').fadeOut();
xmlhttp = createXHR();
xmlhttp.onreadystatechange = callback;
var not_valid_email = false;
var your_name = document.getElementById("your_name").value;
var captcha_code = document.getElementById("captcha_code").value;
var subject = document.getElementById("subject").value;
var email = document.getElementById("email").value;
var mobile_number = document.getElementById("mobile").value;
if(mobile_number.length < 10 || mobile_number.length > 14){
var not_valid_mobile = true;
}
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length){
var not_valid_email = true;
}
var message = document.getElementById("message").value;
xmlhttp.open("POST", "contact_process.php" ,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
if((your_name == "" || your_name == null) || (not_valid_mobile) || (not_valid_email) || (message == "" || message == null)){
$('#container_wrapper').scrollTop(0);
document.getElementById("form_results").innerHTML = "<p>Message not sent!</p>";
if(your_name == "" || your_name == null){
document.getElementById("form_results").innerHTML = "<p>Oops! You forgot to fill in a required field!</p>";
}else if(not_valid_email){
document.getElementById("form_results").innerHTML = "<p>The email address you entered is invalid!</p>";
}else if(not_valid_mobile){
document.getElementById("form_results").innerHTML = "<p>The mobile number you entered is invalid!</p>";
}else if(message == "" || message == null){
document.getElementById("form_results").innerHTML = "<p>Oops! You forgot to fill in a required field!</p>";
}
}else{
xmlhttp.send("your_name=" + your_name + "&email=" + email + "&mobile=" + mobile_number + "&subject=" + subject + "&message=" + message + "&captcha_code=" + captcha_code);
}
}
function callback(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
refreshCaptcha();
document.getElementById("form_results").innerHTML = xmlhttp.responseText;
$('#container_wrapper').scrollTop(0);
}
}
html for contact form
<section id="form_area" class="content_box">
<div id="form_results"></div>
<form id ="contact_form" method="post" action="">
<label>Your Name (required)</label>
<input id="your_name" name="your_name" type="text" placeholder="Your Name" onfocus = "checkEnter()">
<label>Your Email (required)</label>
<input id="email" name="email" type="email" placeholder="Email" onfocus = "checkEnter()">
<label>Mobile Number (required)</label>
<input id="mobile" name="mobile" type="text" placeholder="Mobile Number" onfocus = "checkEnter()">
<label>Subject</label>
<input id="subject" name="subject" type="text" placeholder="Subject (Optional)" onfocus = "checkEnter()" >
<label>Your Message (required)</label>
<textarea id="message" name="message" rows="4" type="text" placeholder="Please leave your message here" onfocus = "checkEnter()"></textarea>
<label>Please enter the Captcha below (required). Letters are not case sensitive.</label>
<div id="captcha_wrapper">
<img id="captcha" src="/finalne2/securimage/securimage_show.php" alt="CAPTCHA Image" />
<span id="captcha_refresh"><i class="fa fa-refresh"></i></span>
</div>
<input id="captcha_code" type="text" name="captcha_code" size="10" maxlength="6" onfocus = "checkEnter()" onblur = "checkFields()"/>
<div id="submit_area">
<div id="submit_message" class="menu_level_1 button_style">Send</div>
<div id="pointing_finger"><i class="fa fa-hand-o-left"></i></div>
</div
</form><!--End of contact_form-->
</section><!--End of form_area-->
html for search form:
<div id="search_wrapper" class="menu_level_1">
<div id="search_box">
<form action="search.php" method="get">
<input id="search_content" placeholder="Search website" type="text" name="query" size="40" value="" action="" columns="2" autocomplete="off" delay="1500">
<button id="submit_search" type="submit"><i class="fa fa-search"></i></button>
<input type="hidden" name="search" value="1">
</form>
</div>
</div>
Update:
#Malk thanks for spotting the missing bracket in the closing div of the contact form :) that was indeed the problem :)
Just a guess but maybe try specifying an explicit action attribute in the contact form.
<form id ="contact_form" method="post" action="some_page_here">

Javascript Form Validation- can't validate one variable?

I made a contact form for my website and I want to make validations. This is the HTML:
<form name="contact" method="post" action="Contact.php" onsubmit="return validateForm()" >
<span class="formtext"> name:</span> <input id="nameinput" type="text" name="name" /><br />
<span class="formtext"> email:</span> <input id="mailinput" type="text" name="email" /><br />
<span class="formtext"> message:</span><br /> <textarea id="messageinput" type="text" name="message"> </textarea> <br />
<input id="submitinput" name="submit" type="submit" value="שלח"/>
</form>
This is the JS:
// Contact Form //
function validateForm()
{
var x=document.forms["contact"]["name"].value;
var y=document.forms["contact"]["email"].value;
var atpos=y.indexOf("#");
var dotpos=y.lastIndexOf(".");
var z=document.forms["contact"]["email"].value;
if (x==null || x=="" || y==null || y=="" || z=="" || z==null)
{
alert("Please fill all the details");
return false;
}
else
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=y.length)
{
alert ("Please fill a valid email address");
return false;
}
}
The problem has something to do with the variable 'z'. When I fill the form and send it, I get the "Please fill all the details" alert, even though I did fill the textarea. I know it's the 'z' because if I remove both the variable and the part inside the 'if' that has something to do with var 'z', the problem is solved- but then there is no validation.
The z also handles the email input instead of the message textarea
Try replacing
var z=document.forms["contact"]["email"].value;
by
var z=document.forms["contact"]["message"].value;

Categories

Resources