我正在尝试编写一个文本验证函数,该函数使用ErrorProvider
来警告错误的字符,而不是等待我的SQL数据库拒绝命令。我知道有关参数化查询的所有信息,但这并没有帮助我使用ErrorProvider
。
我发现这篇文章在TSQL中有很好的非法字符功能:http://social.msdn.microsoft.com/Forums/sqlserver/en-US/1430e80f-38ac-4270-b2b3-978215a534d5/most-efficient-way-checking-for-an-invalid-character-in-a-database-field?forum=transactsql
这是我想在LINQ中编写的代码,但我不确定这是否是最好的方法:
create table #t(s varchar(100))
insert into #t values ('This is a test!')
insert into #t values ('This is a test')
select *
from #t
where s like '%[^0-9a-zA-Z_:;<=>? ]%'
drop table #t
这是我尝试将其转换为LINQ to Objects但是有些东西无效:
Private Sub TextBox_TextValidation(ByVal sender As TextBox, ByVal e As System.ComponentModel.CancelEventArgs) _
Handles TextBox_FirstName.Validating
'use TSQL to find illegal characters
Dim dt As New DataTable()
dt.Columns.Add("Text")
dt.Rows.Add(TextBox_FirstName.Text)
Dim myQuery = From row In dt.AsEnumerable
Where row.Item("Text") Like "%[^0-9a-zA-Z_:;<=>? ]%"
Select row
'I'll pretty this up later, just get the info from the query for now
For Each x In myQuery
If x.Item("Text") <> "" Then
ErrorProvider1.SetError(TextBox_FirstName, "You Must Use Alpha Numeric Characters")
Else
ErrorProvider1.Clear()
End If
Next
End Sub
我是否在查询中得到一个空的响应是否将所有“合法”字符放在textBox中。 VS2012,VB.NET
答案 0 :(得分:3)
我认为你有点过分思考。您可以使用正则表达式执行此操作 - 您当前的代码似乎正在尝试在VB.NET中执行T-SQL。 LINQ不是SQL(虽然有相似之处)。
我会废弃整个DataTable
和LINQ方法,并执行以下操作:
Private Sub TextBox_TextValidation(ByVal sender As TextBox, ByVal e As System.ComponentModel.CancelEventArgs) _
Handles TextBox_FirstName.Validating
If (Regex.IsMatch(TextBox_FirstName.Text, "[^0-9a-zA-Z_:;<=>?\s]")) Then
ErrorProvider1.SetError(TextBox_FirstName, "You Must Use Alpha Numeric Characters")
Else
ErrorProvider1.Clear()
End If
End Sub
您需要在代码中添加Imports System.Text.RegularExpressions
,并注意我使用\s
代替作为空格。