如何验证字段长度
我在数据库中有一个 Abc 字段,我想确保用户不会超出数据库中该字段的限制,因此我使用验证“您不能输入超过 50 个字符”。
现在的问题是,由于存储中文、印度文和其他此类语言的内存占用超过 1 个字节,我如何验证长度。
现在发生的情况是,用户输入了 30 个字符,他收到一条显示消息:“您不能输入超过 50 个字符”。
对于解决方案,我知道我可以增加数据库的大小或检查字节长度,但这似乎不是一个好主意。
您会采取什么方法来完成它?
I have a Abc field in the database and I want to make sure that the user doesnot cross the limit of the field in database, therefore I use validation that would say "You cannot enter more than 50 characters".
Now the question is that because the memory to store Chinese,Indic script and other such languages take more than 1 byte how would I validate the length.
What happens right now is that user has input of 30 characters and he gets a display message saying "You cannot enter more than 50 characters".
for solution what I know is I can increase the size of the database or check the byte length but it doesn't seems to be a good Idea.
What approach would you follow to get it done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在数据库中使用 nvarchar 类型,它限制字符数而不是字节数。
Use a nvarchar type in your DB it limits number of characters and not number of bytes.
如果您使用 .Net 和 SQl Server 的 nvarchar 字段,我认为应该没问题。
无论如何,Nvarchar 每个字符存储 2 个字节,因此应该容纳 .net 将毫无问题地传递给它的 unicode 字符串。 (换句话说,如果您在数据库中使用 Nvarchar,.Net 和 SQL 中的长度都以字符为单位,而不是以字节为单位)。
If you're using .Net and SQl Server's nvarchar field, you should be fine I think.
Nvarchar stores 2 bytes per char anyway, so should accommodate the unicode string .net will pass to it with no problem. (in other words, the length in .Net and SQL are both measured in chars, not bytes, if you're using Nvarchar in the database).
如果您的 GUI 使用 WinForms 或 WPF,那么您应该能够在文本字段上设置最大长度,这可以很好地阻止人们输入超过指定字符数的字符,例如,
但是您可以从 VS 设计器中进行设置 - 选择文本框并转到其 MaxLength 属性
If your GUI is in WinForms or WPF then you should be able to set a maximum length on a text field which nicely stops people entering more than the specified no of characters, e.g.
But you can set this from the VS Designer - select the textbox and go to its MaxLength property