• 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

    • Yeah, when I saw that, I wanted to find the nearest nose. You can't find a good nose these days when you need one.
    • Anthropic launches Claude Fable 5, a state-of-the-art AI model that beats OpenAI's GPT-5.5 by Pradeep Viswanathan Back in April, Anthropic announced Claude Mythos Preview, a frontier model with state-of-the-art coding capabilities. Due to the cybersecurity implications that would occur due to the availability of such a powerful model, Anthropic made it available to only a select set of companies around the world. The company's plan was to prepare appropriate guardrails before releasing such a powerful model to everyone. Now, after nearly two months, Anthropic announced Claude Fable 5, its most capable AI model yet for general users. The company also announced Claude Mythos 5, the same underlying model as Fable 5, but with safeguards lifted, making it more suitable for selected cybersecurity and biology use cases. Claude Fable 5 sits a tier above its Opus models and it beats most other generally available models across areas including software engineering, knowledge work, vision, scientific research, and long-running autonomous tasks. To prevent model misuse, when Claude Fable 5 detects certain requests related to cybersecurity, biology, chemistry, or model distillation, the request will be routed to the Claude Opus 4.8 model. Anthropic claims that these safeguards trigger in less than 5% of sessions on average. However, for large organizations working on critical software, Claude Mythos 5 can be availed through Project Glasswing. Later, Anthropic has plans to expand access through a broader trusted access program. As you can notice in the benchmarks above, Fable 5 and Mythos 5 are state-of-the-art on most key AI benchmarks and they are well ahead of OpenAI's frontier model, GPT-5.5. For example, Fable 5 is the new state-of-the-art model for vision tasks. Also, Mythos 5 has the strongest cybersecurity capabilities of any model in the world. Claude Fable 5 and Claude Mythos 5 are priced at $10 per million input tokens and $50 per million output tokens, which is less than half the price of Claude Mythos Preview. Another big change is that Anthropic is making a change to the way they handle business customer data for both Fable 5 and Mythos 5 models. The company will now require 30-day retention for all traffic on both first- and third-party surfaces. Anthropic promises that it won't use the data to train Claude models, instead it will use it against complex and novel attacks. Claude Fable 5 is available today on the Claude API and consumption-based Enterprise plans. It is also included at no extra cost for Pro, Max, Team, and seat-based Enterprise customers from today through June 22. After that, users on those plans will need usage credits to continue using Fable 5, unless Anthropic extends the included access window based on capacity. Developers can access Fable 5 through the Claude API using the claude-fable-5 model name.
    • Dragon's Dogma 2: Dark Arisen expansion to bring snowy region, new updates also coming by Pulasthi Ariyasinghe Capcom had a surprise waiting for Dragon's Dogma fans today in the Nintendo Direct presentation. The company revealed an expansion for the second installment with a name that should be familiar to series veterans. Coming later this year, Dragon's Dogma 2: Dark Arisen is promising a massive new region to explore, new monsters, fresh skills to learn, and more. The studio says players will be heading to the Northern region of the world, named Norgan, to find new secrets about an undying "Fallen Dragon." There will be forgotten relics that the protagonist can find to unlock fresh weapons and skills the expansion is introducing. Players will also be able to find mysterious equipment from a previous Arisen as a part of the expansion, all part of 12 Lost Rites Dungeon Challenges they must complete to gain access. In Neowin's own review, I found Dragon's Dogma 2 to be an impressive RPG when it launched back in 2024, giving the title an 8.5/10 for its class variants, companion system, and immersive exploration. "Once a prosperous region of the kingdom of Vermund, it was abandoned many years ago for reasons unknown," says Capcom about the new region. "Long has it been since any soul traveled its paths. Blanketed in heavy snow, these frigid lands are home to savage hordes and creatures of unbelievable power. Those who are capable of vanquishing such fearsome foes, or those who possess a keen eye for exploration, will find themselves rewarded with powerful relics." Dragon’s Dogma 2: Dark Arisen expansion launches on October 9, 2026, with a $29.99 price tag. Ahead of the expansion release, Capcom is also planning to release two free updates to the base game. The first will land tomorrow, June 10, bringing more accessible fast travel with an Eternal Ferrystone and other quality-of-life adjustments. The second update will land sometime in August, aiming to improve frame rates, add more save slots, and bring even more community-requested adjustments. This expanded Dark Arisen edition is also launching on the Nintendo Switch 2 on the same day the content comes to PC, Xbox Series X|S, and PlayStation 5.
  • Recent Achievements

    • Week One Done
      rubentuben8 earned a badge
      Week One Done
    • Week One Done
      ARaclen earned a badge
      Week One Done
    • One Year In
      jojodbn earned a badge
      One Year In
    • One Month Later
      jojodbn earned a badge
      One Month Later
    • Week One Done
      jojodbn earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      525
    2. 2
      PsYcHoKiLLa
      231
    3. 3
      +Edouard
      124
    4. 4
      ATLien_0
      87
    5. 5
      Steven P.
      83
  • Tell a friend

    Love Neowin? Tell a friend!