Page 1 of 1

string starts with x or y

Posted: Thu Jul 22, 2010 11:24 am
by IGGt
I'm trying to set up some javascript to check a MySQL query before it gets processed. It needs to check that the query starts with either 'SELECT' or 'SHOW', as these are the only two actions permitted. I also want it to check that there is only one ';' and that it is at the end.

I was doing fine, until I tried to add in the OR (SELECT OR SHOW) part. what I have thus far is:

Code: Select all

function sqlcheck(str) {

		var se1="SELECT"
		var se2="SHOW"
		var sc=";"
		var lse1=str.indexOf(se1)
		var lse2=str.indexOf(se2)
		var lstr=str.length
		var lsc=str.indexOf(sc)
		
		if ((str.indexOf(se1)!=0)||(str.indexOf(se2)!=0)){
		   alert("Start with SELECT or SHOW")
		   return false
		}

		if (str.indexOf(sc)!=str.length-1){
		   alert("end with a ;")
		   return false
		}

 		 return true					
	}

function ValidateForm(){
	document.MySQL_Query.query.value = document.MySQL_Query.query.value.toUpperCase();
	
	var query=document.MySQL_Query.query
	
	if ((query.value==null)||(query.value=="")){
		alert("Please Enter a MySQL Query")
		qyery.focus()
		return false
	}
	if (sqlcheck(query.value)==false){
		query.value=""
		query.focus()
		return false
	}
	return true
 }
what can I do to pick up the two options?

Re: string starts with x or y

Posted: Thu Jul 22, 2010 11:46 am
by kaszu
I would use regular expression, but that's just me.

Code: Select all

if ((str.indexOf(se1)!=0)||(str.indexOf(se2)!=0)){
//Currently: if string doesn't start with SELECT or string doesn't start with SHOW
//But if it starts with SELECT, then of course it doesn't start with SHOW, so this
//condition always will be true

//It should be AND instead of OR, correct:
if ((str.indexOf(se1)!=0)&&(str.indexOf(se2)!=0)){

Re: string starts with x or y

Posted: Thu Jul 22, 2010 12:40 pm
by pickle
You're doing some server-side testing as well right?

Re: string starts with x or y

Posted: Fri Jul 23, 2010 9:59 am
by IGGt
kaszu wrote:

Code: Select all

//It should be AND instead of OR, correct:
if ((str.indexOf(se1)!=0)&&(str.indexOf(se2)!=0)){
I think I can see how that makes sense now. And most importantly, it works. cheers. This is my first outing with javascript, so hopefully it'll get better.

(also, the PHP to check the query is coming next, but I figured this would be a good chance to take a look at some javascript - it's only a development system so far, and not being used live).

cheers