Does anyone know the 'test'-function?

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
StumpDK
Forum Commoner
Posts: 35
Joined: Thu Feb 12, 2004 2:28 am
Location: Copenhagen, Denmark

Does anyone know the 'test'-function?

Post by StumpDK »

Could someone explain me why this scripts works? I've searched after a description of the 'test'-function, but I simply can't find one. And the syntax of the email-data doesn't make any sense to me... :?:

Code: Select all

var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
  
  if (!email.test(formObj.value)){

      alert('this is not a valid email adress');
  
  }
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

email is a RegExp object, test() is a method that runs the RegExp pattern (supplied at creation time) against the value passed to it. If the value matches, it returns true/non-zero and false/zero if it fails.
StumpDK
Forum Commoner
Posts: 35
Joined: Thu Feb 12, 2004 2:28 am
Location: Copenhagen, Denmark

Post by StumpDK »

Well, thanks alot! :D Didn't know the RegExp...
StumpDK
Forum Commoner
Posts: 35
Joined: Thu Feb 12, 2004 2:28 am
Location: Copenhagen, Denmark

Reg Exp - test

Post by StumpDK »

Whats wrong with this code? The function returns the alert 'Have to be four digits' if I type less than four digits, but if I type more, it still returns the 'OK'... I would like it to return 'OK' only if there are exactly four digits...

Code: Select all

function isOrderNumber(formObj){
		
		var str = formObj.value;
		
		alert(str);
		
		var orderNumber = /\d{4}/
		
		if(orderNumber.test(str)){
			alert('OK');
		}
		else
			alert('Have to be four digits');
	}
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

the regexp looks for 4 digits anywhere in the value tested against it.

Code: Select all

var orderNumber = /^\d{4}$/;
requries the entire string to be 4 digits.
Post Reply