Javascript Email Validation from Form Field suddenly doesn't work? - javascript

Working on a web page which used to have a working email validation, but after adding in a few additional features it suddenly no longer works. The page shouldn't proceed unless all fields are valid, everything is basically client-side if you're wondering why it's a bit of a weird website.
Originally the e-mail validation worked for if the field was blank or did not have an '#' and '.' following it, using the code:
if (d==null || d=="")
{
document.forms["registration"]["email"].focus();
alert("Please enter your email address");
return false;
}
else
{
var emailAddress = d;
var atLoc = emailAddress.indexOf("#",1);
var dotLoc = emailAddress.indexOf(".",atLoc+2);
var len = emailAddress.length;
if (atLoc > 0 && dotLoc > 0 && len > dotLoc+2)
{
return true;
}
else
{
alert("Invalid E-mail address format! Please enter your e-mail address again.");
document.forms["registration"]["email"].focus();
return false;
}
}
However, added with the entire code of:
function validateForm(){
{
var f=document.forms["registration"]["FirstName"].value;
var a=document.forms["registration"]["Surname"].value;
var b=document.forms["registration"]["address"].value;
var c=document.forms["registration"]["post"].value;
var d=document.forms["registration"]["email"].value;
var z=document.forms["registration"]["password"].value;
if (f==null || f=="")
{
document.forms["registration"]["FirstName"].focus();
alert("Please enter your first name");
return false;
}
if (a==null || a=="")
{
document.forms["registration"]["Surname"].focus();
alert("Please enter your surname");
return false;
}
if (b==null || b=="")
{
alert("Please enter your address");
document.forms["registration"]["address"].focus();
return false;
}
if (c==null || c=="")
{
alert("Please enter your postcode");
document.forms["registration"]["post"].focus();
return false;
}
if (d==null || d=="")
{
document.forms["registration"]["email"].focus();
alert("Please enter your email address");
return false;
}
else
{
var emailAddress = d;
var atLoc = emailAddress.indexOf("#",1);
var dotLoc = emailAddress.indexOf(".",atLoc+2);
var len = emailAddress.length;
if (atLoc > 0 && dotLoc > 0 && len > dotLoc+2)
{
return true;
}
else
{
alert("Invalid E-mail address format! Please enter your e-mail address again.");
document.forms["registration"]["email"].focus();
return false;
}
}
}
}
It no longer works...? Puzzled, any help appreciated.

Related

How to I validate a password using regular expressions in javascript?

This is my code. It functions perfectly up to the password validation. It completely ignores my null test and goes straight to the actual validation but then refuses to go past it and keeps giving me my invalid password alert. Any ideas as to how to fix this issue?
function validate(){
var l = document.getElementById('lname').value;
var f = document.getElementById('fname').value;
var e = document.getElementById('email').value;
var e2 = document.getElementById('cemail').value;
var u = document.getElementById('newuser').value;
var p = document.getElementById('newpass');
var p2 = document.getElementById('cnewpass');
var str = new RegExp(/[a-zA-Z]{1,30}$/);
var em = new RegExp(/[a-z0-9._-]+#[a-z]+\.[a-z]{1,30}$/);
var pass = new RegExp(/[a-zA-Z0-9]{1,15}$/);
if (l == null || l == ""){
alert("Please enter your last name");
return false;
}
var ln = str.test(l);
if(ln==false){
alert("Invalid Name.");
documents.forms['registration']['lname'].focus;
return false;
}
if (f == null || f == ""){
alert("Please enter your first name");
return false;
}
var fn = str.test(f);
if(fn==false){
alert("Invalid Name.");
documents.forms['registration']['fname'].focus;
return false;
}
if (e == null || e == "") {
alert("Please enter an email address");
return false;
}
if (e2 == null || e2 == "") {
alert("Please enter an email address");
return false;
}
var eml = em.test(e);
if(eml==false){
alert("Invalid Email.");
documents.forms['registration']['email'].focus;
return false;
}
var eml2 = em.test(e2);
if(eml2==false){
alert("Invalid Email.");
documents.forms['registration']['cemail'].focus;
return false;
}
if(e2!=e){
alert("Please ensure that the emails match.");
return false;
}
if (u == null || u == "") {
alert("Please enter a user name");
return false;
}
var un = str.test(u);
if(un==false){
alert("Invalid user name");
documents.forms['registration']['newuser'].focus;
return false;
}
if (p == null || p == "") {
alert("works");
alert("Please enter a password");
return false;
}
if (p2 == null || p2 == "") {
alert("Please enter a password");
return false;
}
var pwrd = pass.test(p);
if(pwrd==false){
alert("Invalid Password.");
documents.forms['registration']['newpass'].focus;
return false;
}
if(p2!=p){
alert("Please ensure that the passwords match");
documents.forms['registration']['cnewpass'].focus;
return false;
}
}
You should amend js code that retriving data from from. Look,
var p = document.getElementById('newpass');
var p2 = document.getElementById('cnewpass');
Here You are trying to get NOT values of input tags, you are trying to get tag.
So You should replace above code with:
var p = document.getElementById('newpass').value;
var p2 = document.getElementById('cnewpass').value;
I hope it will help you
You should pass the value of password fields.
try changing the code to
var p = document.getElementById('newpass').value;
var p2 = document.getElementById('cnewpass').value;

Javascript Form Validation check

I am doing some homework about form validation and have write some code but it is not valid with some problems. Can someone tell me what's wrong in them and fix them? Thanks
function formCheck() {
var form = document.forms["contact_form"];
if(form["first_name"]["last_name"].value == "") {
alert("Please fill in the required name.");
form["first_name"]["last_name"].focus();
return false;
}
var zip = /^\d{5}(-\d{4})?$/.test;
if(zip.test(form["zip_code"]).value == false){
alert("Please fill in a valid zipcode.");
form["zip_code"].focus();
return false;
}
var phone = /^\[0-9]{10}$|^\([0-9]{3}\)[ ]?[0-9]{3}-[0-9]{4}$/
if(phone.test(form["phone_number"]).value == false){
alert("Phone number input format is not valid.");
form["phone_number"].focus();
return false;
}
var email = /^([a-zA-Z0-9_.])+#[a-zA-Z0-9]([a-zA-Z0-9])+\.([a-z])+$/
if(email.test(form["email_address"].value == false){
alert("Email format is not valid.");
return false;
}
form.submit();
return true;
}
This seems incorrect:
if(form["first_name"]["last_name"].value == "") {
alert("Please fill in the required name.");
form["first_name"]["last_name"].focus();
return false;
}
You may want to replace that with:
if(form["first_name"].value == "") {
alert("Please fill in the required first name.");
form["first_name"].focus();
return false;
}
if(form["last_name"].value == "") {
alert("Please fill in the required last name.");
form["last_name"].focus();
return false;
}

Jquery form validation coding

My Jquery validation is not working, below is the script coding. I am getting a
Fatal error: Uncaught exception
error and not sure why. I know one of the reasons can be the validation code isnt correct. Is the coding correct or is there errors?
<script type="text/javascript">
$('form#contact').submit(function(e) {
var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(jQuery('#form_zip').val());
var isValidYear = /^\d{4}$/.test(jQuery('#gradDate').val());
var year_number = parseInt(jQuery('#gradDate').val());
var isValidEmail = /^(([^<>()[\]\\.,;:\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,}))$/.test(jQuery('#form_email').val());
var first_name = jQuery.trim(jQuery('#first_name').val());
var last_name = jQuery.trim(jQuery('#last_name').val());
var form_email = jQuery.trim(jQuery('#form_email').val());
var street = jQuery.trim(jQuery('#street').val());
var city = jQuery.trim(jQuery('#city').val());
var state = jQuery.trim(jQuery('#state').val());
var isValidPhone = /^[2-9]\d{2}[2-9]\d{2}\d{4}$/.test(jQuery('#phone_day').val());
function validZip(zip)
{
if (zip.match(/^[0-9]{5}$/)) {
return true;
}
zip=zip.toUpperCase();
if (zip.match(/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/)) {
return true;
}
if (zip.match(/^[A-Z][0-9][A-Z].[0-9][A-Z][0-9]$/)) {
return true;
}
return false;
}
if(!validZip(jQuery('#form_zip').val())){
alert('Please enter a valid Zip Code.');
}
else if(!isValidYear || (year_number > <?php echo date('Y')?>)){
alert('Please enter a valid High School Graduation Year.');
}
else if(!isValidEmail (jQuery('#form_email').val())){
alert('Please enter a valid Email Address.');
}
else if(first_name.length <= 0 || first_name == 'First Name' || (!first_name.match(/[a-zA-Z]/)) || (first_name.match(/[0-9]/))){
alert('Please enter your First Name.');
}
else if(last_name.length <= 0 || last_name == 'Last Name' || (!last_name.match(/[a-zA-Z]/)) || (last_name.match(/[0-9]/))){
alert('Please enter your Last Name.');
}
else if(street.length <= 0 || street == 'Street Address'){
alert('Please enter your Street Address.');
}
else if(city.length <= 0 || city == 'City'){
alert('Please enter your City.');
}
else if(state.length <= 0 || state == 'State'){
alert('Please enter your State by 2 letter abbreviation.');
}
else if(country.length <= 0 || country == 'Other'){
alert('Please enter your Country.');
}
else if(!isValidPhone){
alert('If your phone number is correct, close this box and then Click the button in the form.');
}
else {
$('form#mainform').submit();
}
return false;
}
return false;
}
});
</script>
You have php inside your JavaScript code:
else if(!isValidYear || (year_number > <?php echo date('Y')?>)){

Conditional valdiation of required fields

I have a page where the user enters their address. I want to make city, state and zip code required fields, but here's the catch. Either the user is required to enter both the city and the state OR they are required to enter the zip code. How do I do this javascript?
For now I have
function Form(f) {
for (var n = 0; n < f.elements.length; n++) {
if ((f.elements[n].name).indexOf("zip_code") > -1) {
var zipcode = f.elements[n].value;
if (zipcode.length == "") {
if ((f.elements[n].name).indexOf("cityname") > -1) {
var city = f.elements[n].value;
if (city.length == "") {
alert("Enter City name");
break;
}
}
if ((f.elements[n].name).indexOf("statename") > -1) {
var state = f.elements[n].value;
if (state.length == "") {
alert("Enter State name");
break;
}
}
} else {
//return true; then do something
return false;
}
} else if (zipcode.length == "") {
alert("Enter zipcode");
break;
return false;
}
}
}
Can you please try this?
function Form(f) {
var cityname = document.getElementsByName('cityname')[0].value;
var statename = document.getElementsByName('statename')[0].value;
var zip_code = document.getElementsByName('zip_code')[0].value;
if( (cityname.length==0 && statename.length==0 ) ){
if(zip_code.length==0){
alert("Enter zipcode");
return false;
}
return true;
}else if( (cityname.length==0 || statename.length==0 ) ){
if (cityname.length == 0) {
alert("Enter City name");
return false;
}else if (statename.length == 0) {
alert("Enter State name");
return false;
}
return true;
}
}
Something like this should help
if( zipcode.length){
/* validate zipcode*/
}else{
if( city.length && state.length){
}else{
/* must have city and state*/
}
}
use a variable flag.
flag = 0;
if city and state
make flag as 1
if zip
make flag as 1
if flag==0 then validation failed
else allow to submit form

nested if else in javascript

I have trouble with the nested if structure in javascript. Any help is appreciated.
function validateForm()
{
var a = document.forms["demo1"]["addr1"].value;
var b = document.forms["demo1"]["city"].value;
//var c = document.forms["demo1"]["fname"].value;
//var d = document.forms["demo1"]["lname"].value;
//var f = document.forms["demo1"]["phno"].value;
//var g = document.forms["demo1"]["email"].value;
//var g1 = document.forms["demo1"]["cemail"].value;
//var h = document.forms["demo1"]["pwd"].value;
//var h1 = document.forms["demo1"]["cpwd"].value;
if(b=="" || b==null)
{
alert("Please enter your city");
return false;
break;
}
else if(a=="" || a==null)
{
alert("Please enter your address");
return false;
break;
}
else {return true;}
}
<form name = "demo1" action = "exp2.php" onsubmit = "return validateForm()" method = "POST">
The code works fine(as intended) if there is only one if statement. But I am not getting the intended result if more than one if else is been deployed.
Regards,
Mani
First, you don't need break statements, they're useless in this context.
Second, you don't need to nest and, in fact, you shouldn't since checking of a and b is independent of each other:
if(b=="" || b==null)
{
alert("Please enter your city");
return false;
}
if(a=="" || a==null)
{
alert("Please enter your address");
return false;
}
return true;
What about shorten ur code with reusable isEmpty function
function validateForm()
{
var isEmpty = function ( name , label ){
var val = document.forms["demo1"][ name ].value;
if( ! val )
{
alert("Please enter your "+ label );
return true;
}
return false;
}
return !isEmpty( 'city', 'city') &&
!isEmpty( 'addr1', 'address');
}
isEmpty return true or false
if(b=="" || b==null) {
alert("Please enter your city");
return false;
}
else if(a=="" || a==null) {
alert("Please enter your address");
return false;
}
else {
return true;
}
Like paxdiablo says you can use two separate if statements.
But if you only want to require an address when a city is entered you must realize that this is not a nested if statement. This is:
if(b=="" || b==null)
{
alert("Please enter your city");
return false;
}
else
{
if(a=="" || a==null)
{
alert("Please enter your address");
return false;
}
else
{
return true;
}
}
A more reabable version would be, imo:
if(b=="" || b==null)
{
alert("Please enter your city");
return false;
}
if((b=="" || b == null) && (a=="" || a==null))
{
alert("Please enter your address");
return false;
}

Categories

Resources