I would like to check my passwordTextField while editing. I have three different criteria:
at least 8 characteres
at least 1 upper and lowercase letter
at least 1 digit
I already have this function which I need afterwards for checking all three cases at once:
static func isPasswordValid(_ password : String) -> Bool {
let passwordTest = NSPredicate(format: "SELF MATCHES %#", "^(?=.*[A-Z]).(?=.*[0-9]).(?=.*[a-z]).{8,}$")
return passwordTest.evaluate(with: password)
}
But for now I need to check the different cases separately while editing my textField.
I basically need 3 different regex checks inside some sort of whileEditing method I am stuck here...
Is there an easy way to get this done?
Use the UITextField EventListner method, to check your conditions. You can also set the below in Nibs or Storyboards,
textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
This passwordTest.evaluate(with: password) returns a result of unknown predicate hit so you have to separate them to handle what you need e.x there may be 8 charaters but no digits between them
Related
I need to set UITextField for nickname. It need to be english only, lowercase, underscore and numbers. Really don't know how to do that and can't find any information. Thanks for your time!
you can create a regex for this & comparison textfield value with your regex pattern.
func isValidName(name:String)-> Bool {
let nameRegEx = "^[a-z0-9_]+$" // this mean you can only use lower case a-z, 0-9 and underscore
let namelTest = NSPredicate(format:"SELF MATCHES %#", nameRegEx)
return namelTest.evaluate(with: name)
}
use this method and vaidate textfield value by pasting as parameter function.
if return true it means username passed validation.
if return false you can show an error to user or shake textfiled and set red color for textfield.text or placeholder color or any thing you want.
hope to this help you.
I want to check if the first three characters entered in the UI Textfield are numbers. I could do this easily in Python, but for some reason in Swift it's a pain.
Here's my python if statements (which I want to 'translate' into swift as it works):
str = "123abc"
if str.isdigit():
if str[:3]:
print(str)
and here's my swift code
#IBOutlet weak var input: UITextField!
#IBAction func checkBarcodeRegion(_ sender: UIButton)
{
let text: String = input.text!
if text.prefix(3)
{
//if numeric
//do something
}
}
Can't get this to work. Any help appreciated.
Three alternatives:
Create an Int from the substring and check if for non-nil.
let isNumeric1 = Int(text.prefix(3)) != nil
Remove all digits from the substring with Regular Expression and check for empty string
let isNumeric2 = text.prefix(3).replacingOccurrences(of: "[0-9]", with: "", options: .regularExpression).isEmpty
Split the substring by the decimalDigits character set and check if the number of components is 4
let isNumeric3 = text.prefix(3).components(separatedBy: .decimalDigits).count == 4
Using prefix is the right direction to go. You can use allSatisfy after that to check if they are all digits. One of the ways to check for digits is to check if the unicode scalar is in the CharacterSet.decimalDigits set.
text.unicodeScalars.prefix(3)
.allSatisfy(CharacterSet.decimalDigits.contains)
This will check for all the digits in Unicode, including the ones that the Indians and Arabic use.
If by digits you mean the ASCII 0123456789, then you could use:
text.prefix(3).allSatisfy(("0"..."9").contains)
I am using xcode8+swift3.
I have multiple UITextField in my controller view. Each UITextField has a outlet connection in code.
I know I can use “tag” to identify UITextField, but it seems I can only use number as tag (I tried with string value for tag field, my Xcode always get stuck, only number as tag works).
But I don’t want to use magic number in my code like:
If (textField.tag == 0) {
}
I am wondering, is there a better way or more descriptive way in code to identify UITextField?
Tag is the correct tool. Just create an enum for them to track.
enum FieldIdentifier: Int {
case name = 0
case age = 1
}
if let fieldIdentifier = FieldIdentifier(rawValue: textField.tag) {
switch fieldIdentifier {
case .name: ...
case .age: ...
}
}
(Note that Larme's comment about using == is also appropriate, and if you already have outlets is better.)
I'm Using Swift 3 and firebase to create a social app where users can make posts but the thing is that I don't want the users to use curse words.
Is there a way like to replace these words when the users writes them?
Currently the users use a text view to write the things they want to post...
How can I do it in like the easiest and simple way?
I was looking for answers and I find this question Swift: how to censor/filter text entered for swear words, etc?.
With this answer code:
import Foundation
func containsSwearWord(text: String, swearWords: [String]) -> Bool {
return swearWords
.reduce(false) { $0 || text.contains($1.lowercased()) }
}
// example usage
let listOfSwearWords = ["darn", "crap", "newb"]
/* list as lower case */
let userEnteredText1 = "This darn didelo thread is a no no."
let userEnteredText2 = "This fine didelo thread is a go."
print(containsSwearWord(text: userEnteredText1, swearWords: listOfSwearWords)) // true
print(containsSwearWord(text: userEnteredText2, swearWords: listOfSwearWords)) // false
But I don't really get it. How can I implement that in my project? Where should I paste that code? Or how can I link that code to my text view? And what it´s missing on that code to work as it should be?
If you use UITextField on .editingChanged event.
inputTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
func textFieldDidChange(_ textField: UITextField) {
print(containsSwearWord(text: textField, swearWords: listOfSwearWords)) // Here you check every text change on input UITextField
}
UPDATE
You must implement UITextViewDelegate (Official Documentation)
Validate before input ends
In textViewShouldEndEditing(_ textView: UITextView) validate user input and return true/false to allow editing end.
Validate after input ends
In textViewDidEndEditing(_ textView: UITextView) validate user input and show any warning if you found not allowed words.
This is how I would do it.
Pass TextView text to NSString
Convert NSString to NSArray
Check to see if that NSArray contains one of your curse string. If it does then do replace it with **** or something.
This is how it would look in objective-C.
NSString *textViewStr = myTextView.text;
NSArray *myArray1 = [textViewStr componentsSeparatedByString:#" "]; //this will put all words separated by space into an array
if ( [myArray1 containsObject:#"crap"] ) {
//found one
textViewStr = [textViewStr stringByReplacingOccurrencesOfString:#"crap"
withString:#"duck"];
}
while googling I found another better answer.
//If you want multiple string replacement:
NSString *s = #"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:#"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: #""];
NSLog(#"%#", s); // => foobarbazfoo
String replacement in Objective-C
I am making calculator in Swift. Stuck in backspace button. If user press wrong digit then backspace button would help to delete digit off the display.
Though I wrote dropLast function and works. It return appropriate result. How to use count method, don't understand the return type of count method.
#IBOutlet weak var display: UILabel!
#IBAction func backspace() {
//how to use count method to check collection of elements
//dropLast drop the last digit and display result
let dropedDigit = dropLast(display.text!)
display.text = dropedDigit
}
How about something like this:
private func dropLast(text: String) -> String {
let endIndex = advance(text.endIndex, -1)
return text.substringToIndex(endIndex)
}
It calculates the index where you want to make the cut (endIndex of text - 1) and then returns the substring to this index. This function should drop the last character.
I am not using count method here, but for you reference Swift 1.2 introduces count(<#x: T#>) method that calculates length of sets including Strings.
I know this thread is outdated, but I just went through the process of making this work, myself, in Swift 2.2, and figured I could help answer it.
#IBAction func delButton(sender: AnyObject) {
if display.text != nil {
var tempString = Array(display.text!.characters)
tempString.removeLast(1)
display.text = ""
for num in 0..<tempString.count {
display.text = display.text! + String(tempString[num])
}
}
}
Basically, we're checking to see that the display label has stuff in it, so we don't throw an error, and if so, making a variable in the scope of the function to hold the label's characters individually in a string. After that, we remove the last character from the array, clear out the label to ensure we aren't adding what's already there to our new values, then iterating through the updated array of characters and adding it to the label.
It's important to note that we are casting the values contained in the array as String, because they've been put into the array as character values, which operate differently than the string value the label is expecting.
Like I said, I know the thread is a little out of date, but I've been going through courses in Swift, and have discovered that while there is a plethora of information out there for Objective-C, there is perilously little information out there for how to do a lot of those things in Swift. Since the language is being updated repeatedly, I've noticed a growing divide between the two languages.