Jump to content



Photo

[Javascript] Form Validation


  • Please log in to reply
12 replies to this topic

#1 Axel

Axel

    --[Est. 1986]--

  • Joined: 05-August 03
  • Location: Milton Keynes, UK

Posted 29 January 2013 - 15:22

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.


#2 Tuishimi

Tuishimi

    Michinator

  • Joined: 19-November 10
  • OS: Windows 8

Posted 29 January 2013 - 15:51

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"...

#3 spacer

spacer

    I'm awesome

  • Joined: 09-November 06
  • Location: Connecticut, USA
  • OS: Windows 7
  • Phone: Nexus 4

Posted 29 January 2013 - 15:56

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.

#4 OP Axel

Axel

    --[Est. 1986]--

  • Joined: 05-August 03
  • Location: Milton Keynes, UK

Posted 29 January 2013 - 19:11

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 <img src='http://www.neowin.net/forum/public/style_emoticons/<#EMO_DIR#>/smile.png' class='bbc_emoticon' alt=':)' />");
    } 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 < currentYear) {
        var intmessage = "Credit Card has expired\n";
    }
    else
    {
        if (expiryMonth < 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!

#5 spacer

spacer

    I'm awesome

  • Joined: 09-November 06
  • Location: Connecticut, USA
  • OS: Windows 7
  • Phone: Nexus 4

Posted 29 January 2013 - 19:31

Glad to hear you're humming along again. I sometimes get stumped on those simple mix-ups too. Sometimes all it takes is another set of eyes.

#6 palenous

palenous

    Neowinian

  • Joined: 19-January 13
  • Location: Ohio, United States
  • OS: Windows 7 Ultimate
  • Phone: Samsung Galaxy SIII (Verizon)

Posted 29 January 2013 - 20:41

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 <img src='http://www.neowin.net/forum/public/style_emoticons/<#EMO_DIR#>/smile.png' class='bbc_emoticon' alt=':)' />");
	} 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 < currentYear) {
		var intmessage = "Credit Card has expired\n";
	}
	else
	{
		if (expiryMonth < 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;

I believe it should be written as:

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

Please correct me if I'm wrong though.

#7 OP Axel

Axel

    --[Est. 1986]--

  • Joined: 05-August 03
  • Location: Milton Keynes, UK

Posted 29 January 2013 - 21:06

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

#8 PhilTheThrill

PhilTheThrill

    Neowinian Senior

  • Joined: 28-November 03
  • Location: Canada
  • OS: Win 8.1
  • Phone: WP8

Posted 29 January 2013 - 21:15

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">
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.

#9 OP Axel

Axel

    --[Est. 1986]--

  • Joined: 05-August 03
  • Location: Milton Keynes, UK

Posted 29 January 2013 - 21:29

As much as I'm an advocate for simplicity, this is going to have to relatively cross-browser compatible so the javascript validation seems to be the best option :)

#10 OP Axel

Axel

    --[Est. 1986]--

  • Joined: 05-August 03
  • Location: Milton Keynes, UK

Posted 29 January 2013 - 22:14

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 > 31
			&& (charCode < 48 || charCode > 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!

#11 OP Axel

Axel

    --[Est. 1986]--

  • Joined: 05-August 03
  • Location: Milton Keynes, UK

Posted 30 January 2013 - 11:14

*bump*

#12 spacer

spacer

    I'm awesome

  • Joined: 09-November 06
  • Location: Connecticut, USA
  • OS: Windows 7
  • Phone: Nexus 4

Posted 30 January 2013 - 14:19

How are you linking the external files? It may be helpful to post your entire html and javascript files so that we can see what you're doing.

#13 OP Axel

Axel

    --[Est. 1986]--

  • Joined: 05-August 03
  • Location: Milton Keynes, UK

Posted 30 January 2013 - 19:42

I've been an idiot, I just realised if I stick the whole lot in a file and then link it in the body it all works. Apologies for the confusion!