• 0

[Javascript] Form Validation


Question

Trying to add some validation stuff to a web form using javascript:

http://jsfiddle.net/rGxP6/


function verifyForm(){
var emailStatus = false;
var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
	 if (document.getElementById('email').value.search(emailRegEx) == -1) {
emailStatus = false
		  alert("False");
	 }
	 else {
		  emailStatus = true;
		  alert("True");
	 }
	 return emailStatus;
}

Keeping it simple to start with I thought I'd start by validating one thing, that being the email address. I found the regex for email address's online. I am on a bit of a learning curve at the moment and appreciate the help you guys have been giving me.

I loaded the chrome console up and noticed that it said verifyForm was not defined. I've tried to load the js above using onlick for the time being to verify the code works.

Here's the HTML:


<input id="email" type="text">
<input type="submit" onclick="verifyForm();" value="verify">

I imagine as usual it's something simple I've overlooked!

Many thanks,

Alex

Edit: Off out for a bit shall return in an hour or so.

Link to comment
https://www.neowin.net/forum/topic/1133556-javascript-form-validation/
Share on other sites

12 answers to this question

Recommended Posts

  • 0

I don't know... you could try putting the regex in quotes. I tried it both ways and it worked for me in Chrome. What does your whole page look like? I threw the JS into the <head><script> section... but yeah, it verified the email address and correctly popped up "true" or "false"...

  • 0

Your fiddle set up is incorrect. You have your framework setting set to "onload". If you right-click your "result" pane and select "view frame source" you can see that your verify function is defined inside the window.onload function. Which means it's not accessible outside of that context.

Try setting your fiddle to "head (no wrap)" which will put whatever is in your javascript frame directly into the head of your document.

  • 0

That's awesome - simple mistake on my part.

Been playing with validating the form today and so far I have this:


function verifyForm(){
var message = "";
message += verifyEmail1();
message += verifyExpiry();
    if (message == "") {
        alert("No errors found :)");
    } else {
    alert("The following errors have been found:\n\n"+message);
    }
}

function verifyEmail1(){
var intmessage = "";
var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
     if (document.getElementById('email').value.search(emailRegEx) == -1) {
 var intmessage = "You must enter a valid e-mail address\n";
     }
    return intmessage;
}

function verifyExpiry() {
var intmessage = "";
today = new Date();
var currentYear = parseInt(today.getFullYear().toString(10).substring(2, 4));
var currentMonth = today.getMonth() +1;
var expiryYear = document.getElementById('year').value;
var expiryMonth = document.getElementById('month').value;
    if (expiryYear &lt; currentYear) {
        var intmessage = "Credit Card has expired\n";
    }
    else
    {
        if (expiryMonth &lt; currentMonth) {
            var intmessage = "Credit Card has expired\n";
        }
    }
   return intmessage;
}

http://jsfiddle.net/rGxP6/20/

Done lot's of playing and so far so good!

  • 0

That's awesome - simple mistake on my part.

Been playing with validating the form today and so far I have this:


function verifyForm(){
var message = "";
message += verifyEmail1();
message += verifyExpiry();
	if (message == "") {
		alert("No errors found :)");
	} else {
	alert("The following errors have been found:\n\n"+message);
	}
}

function verifyEmail1(){
var intmessage = "";
var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
	 if (document.getElementById('email').value.search(emailRegEx) == -1) {
var intmessage = "You must enter a valid e-mail address\n";
	 }
	return intmessage;
}

function verifyExpiry() {
var intmessage = "";
today = new Date();
var currentYear = parseInt(today.getFullYear().toString(10).substring(2, 4));
var currentMonth = today.getMonth() +1;
var expiryYear = document.getElementById('year').value;
var expiryMonth = document.getElementById('month').value;
	if (expiryYear &lt; currentYear) {
		var intmessage = "Credit Card has expired\n";
	}
	else
	{
		if (expiryMonth &lt; currentMonth) {
			var intmessage = "Credit Card has expired\n";
		}
	}
   return intmessage;
}

http://jsfiddle.net/rGxP6/20/

Done lot's of playing and so far so good!

It's looking really good so far! One thing I'd like to point out that I'm not 100% sure on is in your emailRegEx variable... don't you have to escape all the '.' as '\.' or am I incorrect about that? I see you did it in part of it, but not all of it:


var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
[/CODE]

I believe it should be written as:

[CODE]
var emailRegEx = /^[A-Z0-9\._%+-]+@[A-Z0-9\.-]+\.[A-Z]{2,4}$/i;
[/CODE]

Please correct me if I'm wrong though.

  • 0

I'm not entirely sure, I found the regex string on stackoverflow and I've attempted to enter a few address's to test and it all seems to be ok?

Truth be told I'm not entirely sure how the regex expression works so I am certainly in no position to correct you! :p

  • 0

If I'm reading your regular expression correctly you're just doing a simple contains @ and . validation?


<input type="email" name="email" required placeholder="Enter a valid email address">
[/CODE]

By specifying the type as "email" and including "required", that'll do it's own validation on an HTML5 document. True it's not quite as robust as a regex but it's a lot less code. If you wanted to match something very specific like only accept emails from "hotmail" then it wouldn't be useful.

  • 0

Quick question and I may as well write it here.

Seeing as the script is going to be relatively long, I may wish to stick it into an external .js file and link it in the document. I already have one which limits input on specific fields to numeric only and that appears to only work if it's in the head of the document. I'll paste it here actually:


	   function isNumberKey(evt)
	   {
		  var charCode = (evt.which) ? evt.which : event.keyCode;
		  if (charCode &gt; 31
			&amp;&amp; (charCode &lt; 48 || charCode &gt; 57))
			 return false;

		  return true;
	   }	  

This seems to be fine sitting in an external file in the head of the document.

onkeypress="return isNumberKey(event)"

is then added to any of the input fields to prevent non-numerical data being entered.

I have another bit of javascript designed to combine the data from two fields into one. However this doesn't work if I stick it in my external .js file linked in the head. For some reason it seems to need to sit in the body to work.


function join_expiry()
{
var mm = document.getElementById('month').value;
var yy = document.getElementById('year').value;
document.getElementById('expiry').value = mm+yy;
}

Below is the code added to the relevant fields.

oninput="join_expiry();"

If anyone could explain these occurances to me it'd very much help my learning!

Many thanks!

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I do trust Apple probably more than these other companies with certain data, but I also do think (and it has been demonstrated that) Apple pulls a lot of shenanigans and always has for a long time.
    • Does your iPhone support the latest iOS version? Here's the iOS 27 compatibility list by Aditya Tiwari It's that time of year when we get to know about the latest operating system updates for Apple devices. For iPhone, Apple previewed the iOS 27 update at WWDC 2026, where the company finally introduced an upgraded version of Siri. Apple typically supports iPhone models for up to five years. But it has been making exceptions in recent years (read iPhone 11). If you're wondering whether your iPhone is compatible with the iOS 27 update, here is the official list of devices: iPhone 17 Pro Max, iPhone 17 Pro, iPhone 17, iPhone 17e, iPhone Air iPhone 16 Pro Max, iPhone 16 Pro, iPhone 16, iPhone 16 Plus, iPhone 16e iPhone 15 Pro Max, iPhone 15 Pro, iPhone 15 Plus, iPhone 15 iPhone 14 Pro Max, iPhone 14 Pro, iPhone 14 Plus, iPhone 14 iPhone 13 Pro Max, iPhone 13 Pro, iPhone 13, iPhone 13 mini iPhone 12 Pro Max, iPhone 12 Pro, iPhone 12, iPhone 12 mini iPhone 11 Pro Max, iPhone 11 Pro, iPhone 11 iPhone SE (2nd generation), iPhone SE (3rd generation) So, you can download the iOS 27 developer beta on up to 31 different iPhone models. There has been no change to the list of supported iPhones since iOS 26. However, it will expand to include more devices when the iPhone 18 series arrives later this year. To download the developer beta on your iPhone, go to Settings > General > Software Update > Beta Updates. Here, select "iOS 27 Developer Beta" from the list of choices to get the new update. In addition to iOS 27, you can try the developer beta versions of macOS 27, iPadOS 27, watchOS 27, tvOS 27, and HomePod software 27 on your supported devices. iOS 27 comes with improved Liquid Glass, which you can adjust using a new transparency slider. Apple said during the keynote that iPhone apps now launch up to 30% faster, new photos appear in the Photos app up to 70% faster, and AirDrop transfers work up to 80% faster. The new update promises to improve performance on older iPhones by introducing a new CPU Scheduler that supports devices all the way back to the iPhone 11. While iOS 27 is supported on older iPhones, it goes without saying that they'll lack several features due to hardware differences. For instance, iPhone 14/14 Plus and older models come with a notch instead of the Dynamic Island. Similarly, Apple Intelligence features are supported on iPhone 15 Pro/Pro Max and later models.
    • The Radeon RX 9070 XT is right up there with the GeForce RTX 5070 Ti
    • I don't know why someone said useless, but it does have that pesky kernel driver bundled, and it's in perennial turmoil. When it goes bad, it goes very bad, and it's impossible to predict when it will due to system differences. I know that they're in the middle of development for a major new version that will include a completely new driver, one that they expect will largely solve the problem, but that's a ways out and it's unproven at this point.
    • doesn't AdGuard let ads through that pay to be let through?
  • Recent Achievements

    • Experienced
      JayZJay went up a rank
      Experienced
    • Reacting Well
      Sir_Timbit earned a badge
      Reacting Well
    • Week One Done
      rubentuben8 earned a badge
      Week One Done
    • Week One Done
      ARaclen earned a badge
      Week One Done
    • Week One Done
      jojodbn earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      524
    2. 2
      PsYcHoKiLLa
      231
    3. 3
      +Edouard
      132
    4. 4
      ATLien_0
      88
    5. 5
      Steven P.
      83
  • Tell a friend

    Love Neowin? Tell a friend!