Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Seek javascript validator

84 views
Skip to first unread message

GIMME

unread,
May 24, 2004, 6:45:33 PM5/24/04
to
Is there a way to confirm that a string has valid Javascript syntax?

Either a client side or server side solution would be ok.

For a client side solution I'd like to confirm that, say :

var a = "function foo { var t='ok'; alert(t); }"

is valid, or for a server side solution that

String a = "function foo { var t='ok'; alert(t); }"

is valid.

Thanks

Stewart Gordon

unread,
May 27, 2004, 1:07:21 PM5/27/04
to
GIMME wrote:

Neither is client-side or server-side.

The first vaguely resembles JavaScript, and the second vaguely resembles
Java.

Each has both client-side and server-side forms.

But does your crosspost mean that you really are looking for a solution
in either language?

Stewart.

--
My e-mail is valid but not my primary mailbox, aside from its being the
unfortunate victim of intensive mail-bombing at the moment. Please keep
replies on the 'group where everyone may benefit.

GIMME

unread,
May 27, 2004, 8:33:51 PM5/27/04
to
Yes. Either language. Java or Javascript.

But the language can not be server-side Javascript (old netscape Livewire).

rh

unread,
May 29, 2004, 1:12:48 AM5/29/04
to
gimme_this...@yahoo.com (GIMME) wrote:
> Is there a way to confirm that a string has valid Javascript syntax?
>
> Either a client side or server side solution would be ok.
>
> For a client side solution I'd like to confirm that, say :
>
> var a = "function foo { var t='ok'; alert(t); }"

The following sample code should provide a check for valid Javascript
syntax.

Note that it could be greatly simplified if you are able to assume the
browser supports try/catch. If not, and the browser (e.g., IE 4.0,
Navigator 3.0) supports window.onerror, it is used in an attempt to
give a slightly more graceful failure. In the latter case,
window.onerror could be further exploited to provide support for the
validation.

validate = null;
validateFunctionText =
' try {'
+ ' var f = new Function(str);'
+ ' return "Validated OK";'
+ ' }'
+ ' catch (e) {'
+ ' return "Validation failed: "+(e.description '
+ ' || e.message || "");'
+ ' }';

function catchError(msg) {
return ! alert("Failed to create validator: "+(msg || "")) ;
}

if (typeof window.onerror != "undefined") {
onerrorSave = window.onerror;
window.onerror = catchError;
validate = new Function("str", validateFunctionText);
window.onerror = onerrorSave;
}
else validate = new Function("str",validateFunctionText);

// Test

var a = "function foo { var t='ok'; alert(t); }" ;

if(validate) alert( validate(a)) ;
else alert("Unable to validate Javascript");

../rh

>
> Thanks

0 new messages