简体   繁体   中英

Validate a SQL WHERE Clause in javascript

How can I validate a string and know if it is a valid SQL where clause. Ex of invalid string: WHERE 1=1 AND EMPRESA = 'CMIP' AND CD_MAQ ==="jjj" Ex of valid string : WHERE 1=1 AND EMPRESA = 'CMIP' AND CD_MAQ ="jjj"

Appreciate your help.

Sorry you cannot do this easily... Unless you fancy writing a SQL Parser in Javascript.

One solution would be to post the query to a backend which runs it in a try catch block and returns if there was an error or not.

I dread to think what the regex/rules list for this validation would be doing it manually.

Why do you want to do this?? Explain your actual goal rather than your suggested solution and we can maybe come up with a better idea... If you are passing a WHERE clause to SQL from a search page as you suggest - this is not the correct way to do it...

Please use Parameterized queries instead.

Also read up on SQL Injection: What is SQL injection?

This is a complicated problem, you're essentially wanting to do is write an SQL interpreter. Obviously these already exist (on database systems of course) but also there are libraries that can do this for you. For Javascript see:

https://github.com/forward/sql-parser

Although, you probably don't want to perform security critical validation only on the client side, although it won't hurt to do it there and then also validate in on the server side before running it (if that is the end goal).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM