您好我对Access女士很陌生,我可以使用您的一些专业知识来提供建议:
我想验证多行文本框的文本,以便用户只能输入2个大写字母--7个数字 - 分号 - 新行。例如,文本框看起来像这样(但是新行上的每个条目,因为我有它,所以enter在文本框中创建一个新行
import UIKit
import MediaPlayer
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let book = Book(title: "Atlas Shrugged", author: "Ayn Rand", pageCount: 10, categories: ["Ethics"], available: true)
save(object: book, filename: "Bookshelf")
let atlasShrugged = retrieve(filename: "Bookshelf") as! Book
print("\(atlasShrugged.title) by \(atlasShrugged.author)")
}
func save(object:NSObject ,filename:String){
//build filepath in doc directory
guard let docs = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else { return }
let path = (docs as NSString).appendingPathComponent(filename)
//save object to path in docs
NSKeyedArchiver.archiveRootObject(object, toFile: path)
}
func retrieve(filename:String) -> AnyObject? {
// Get documents directory
guard let docs = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else { return nil }
//build path to file
let path = (docs as NSString).appendingPathComponent(filename)
//Unarchive from doc directory
let object = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? Book
return object
}
我认为这对验证规则来说太复杂了。我还认为输入掩码太复杂了。我开始研究RegEx来验证文本,但我很想知道如何让代码评估多行文本框中的每一个新行,以便评估整个文本框。我需要进行某种循环吗?
最终,我希望用户在输入错误的文本时得到一个消息框,阻止条目被添加到记录中,并向用户解释他们需要修改他们的条目以使其有效。
答案 0 :(得分:2)
我认为您对RegEx的想法最简单,但您需要添加引用(请参阅代码)。
这应该做你想要的(只需用文本控件替换Text14)
注意 - 我删除了CANCEL = TRUE,因为它会清除用户数据。最好的路线是确保文本框是UNBOUND - 如果有效,如果RegExp验证所有行,你将更新实际字段
Private Sub Text14_BeforeUpdate(Cancel As Integer)
' Requires reference to "Microsoft VBScript Regular Expressions 5.5"
' Under Tools | References
' Add Reference to "Microsoft VBScript Regular Expressions 5.5"
' 2 Capital Letters followed by 7 digits and ";'
Const VALID_LINE As String = "[A-Z]{2}[\d]{7};"
Dim regEx As New RegExp
Dim strData As String ' Read in textbox
Dim varLines As Variant ' Use this to hold lines of text
Dim intNumLines As Integer
Dim intLine As Integer
Dim strLine As String
With regEx
.Global = True
.Multiline = False
.IgnoreCase = False
.Pattern = VALID_LINE
End With
' Replace Text14 with your text box control name
strData = Text14.Value ' Get Data from Text box
' Split data into lines using Carriage Return Line Feed delimiters
varLines = Split(strData, vbCrLf)
' Go thru all lines to check for data issue
intNumLines = UBound(varLines)
For intLine = 0 To intNumLines
strLine = varLines(intLine)
If Not regEx.Test(strLine) Then
MsgBox "Problem with Line #" & (intLine + 1)
' Cancel - if you want to wipe out data
' Cancel = True
Exit Sub
End If
Next
MsgBox "Data Looks Good: All " & intNumLines & " Lines"
End Sub