简体   繁体   中英

Mysql - Check Constraint to restrict HTML code or allow only numbers, alphabets, spaces and hyphens in table column

My main problem is when someone copy paste text from web like whole cell from google sheet this string submit to mysql database <style type="text/css"><!--td {border: 1px solid #ccc;}br {mso-data-placement:same-cell;}--></style><span style="font-size: 10pt; font-family: Arial;" data-sheets-value="{ <style type="text/css"><!--td {border: 1px solid #ccc;}br {mso-data-placement:same-cell;}--></style><span style="font-size: 10pt; font-family: Arial;" data-sheets-value="{

upon reloading this code alter my HTML table structure on page

I try to create a Check Constraint to allow only Numbers, alphabets, spaces and hyphens in that column all others special character (~!@#$%^&*()+{[}]:;'"\\|?><) need to be ignored or removed on row update

I tried below code but unable to stop HTML code from entering the database

ALTER TABLE Table_Name 
ADD CONSTRAINT ck_No_Special_Characters 
       CHECK (Column_Name NOT LIKE '%[^A-Z0-9]%') 

If do not have control over the form input box how can I resolve this problem in MySQL?

You never have control over the form input box. If you've ever assumed that, rethink those solutions because: You can never trust data from a/the client . At least half the people here on StackOverflow know how to manipulate your forms, we can not however change your server code.

What you want is sanitizing before you input it into your database. You can either clean it and insert it, or check if it's clean, if not throw an error. I've made a quick example in PHP:

$cleanVariable = preg_replace("/[^A-Z0-9]/s", '', $variable);

// OR:

if( !preg_match("/^[A-Z0-9]$/s", $variable) ){
    throw new Exception("does not match");
}

And you might want to use strtoupper() to always make it uppercase.


After you've done the server side, you can make the client side prettier for the user .

<!-- Inline isnt preferred, but for demo: -->
<input onChange="cleanThisInput(this.value)" />

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