Page 1 of 1

Does anyone know the 'test'-function?

Posted: Sun Aug 21, 2005 2:05 pm
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');
  
  }

Posted: Sun Aug 21, 2005 3:09 pm
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.

Posted: Sun Aug 21, 2005 3:20 pm
by StumpDK
Well, thanks alot! :D Didn't know the RegExp...

Reg Exp - test

Posted: Mon Aug 22, 2005 11:44 am
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');
	}

Posted: Mon Aug 22, 2005 11:46 am
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.