Files
swiftGrammar/AIGrammar/lib/CommFunc.swift
2024-08-12 10:49:20 +08:00

61 lines
2.2 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// CommFunc.swift
// AIGrammar
//
// Created by oscar on 2024/8/5.
//
import Foundation
class CommonFunc {
static let shared = CommonFunc()
private let profanityList: [String] = ["fuck", "shit", "porn", "习近平", "鸡巴", "阴茎"] // Example profanity words
private init() {} // Private initializer to ensure singleton usage
func validateInputEng(input: String, isSingleWord: Bool = false) -> (isValid: Bool, message: String) {
// Check for profanity
for badWord in profanityList {
if input.lowercased().contains(badWord) {
return (false, globalEnvironment.DirtyInputErrToast)
}
}
// Check characters based on the isSingleWord flag
let pattern = isSingleWord ? "^[A-Za-z]+$" : "^[A-Za-z0-9 .,;:!?'\"@-]+$"
let regex = try! NSRegularExpression(pattern: pattern)
let range = NSRange(location: 0, length: input.utf16.count)
if regex.firstMatch(in: input, options: [], range: range) == nil {
let characterSet = isSingleWord ? "english letters" : "english letters, numbers, and punctuation"
return (false, "Input should only contain \(characterSet).")
}
return (true, "Input is valid.")
}
func validateChineseInput(input: String) -> (isValid: Bool, message: String) {
// Check for profanity
for word in profanityList {
if input.contains(word) {
return (false, globalEnvironment.DirtyInputErrToast)
}
}
// Check if all characters are valid Chinese characters or punctuation
for character in input {
if !character.isPunctuation && !(0x4E00...0x9FFF).contains(character.unicodeScalars.first!.value) &&
!(0x3400...0x4DBF).contains(character.unicodeScalars.first!.value) &&
!(0x20000...0x2A6DF).contains(character.unicodeScalars.first!.value) {
//
let res = self.validateInputEng(input: input)
if !res.isValid{
return (false, "Input contains invalid characters.")
}
}
}
return (true, "Input is valid.")
}
}