Shows the Alert When Uitextfield's Are Full or Empty Swift

Shows the Alert when UITextField's are full or empty Swift

That's a good example to use guard

@IBAction func LoginBtn(sender: AnyObject) {

guard let userName = userNameTF.text where !userName.isEmpty else {
displayMyAlertMessage ("Forget to fill your user name")
return
}

guard let password = passwordTF.text where !password.isEmpty else {
displayMyAlertMessage ("Forget to fill your password")
return
}

// do something with userName and password
}

Check if UITextfield is empty and display alert

you first remove the whitspace first because it also consider as character. So must remove whitespace use below code,

-(NSString *)remove_whitespace:(NSString *)string_data /* Remove whitspace in the string */
{
NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
string_data = [string_data stringByTrimmingCharactersInSet:whitespace];
return string_data;
}

then , count the length of string. if it is greater than 0 go on, else popup error like below,

if([self remove_whitespace:textstring])
{
NSLog(@"work");
}
else
{
NSLog(@"so error");
}

Got it?

Checking if textfields are empty Swift

This post is given a good answer (it's a pity it has no "accepted" mark). Use (self.field.text?.isEmpty ?? true).

Assume your textField is declared as:

    @IBOutlet weak var textField: UITextField!

You can check its emptiness with:

    if textField.text?.isEmpty ?? true {
print("textField is empty")
} else {
print("textField has some text")
}

To use the variables in your edited post:

    let userEmail = userEmailTextField.text;
// Check for empty fields
if userEmail?.isEmpty ?? true {
// Display alert message
return;
}

or:

    // Check for empty fields
if userEmailTextField.text?.isEmpty ?? true {
// Display alert message
return;
}

Having some trouble checking if textfield within alert box is empty

Regardless of the design, to just make your code work:

The problem:

 if textField.text == "" {
check = false
}

This code won't work the way as you expected, the block will be called before it is displayed, not be called when the textfield changed. see this document.

So to fix it, you can just check whether the textfield is empty when user click the save button:

 let saveAction: UIAlertAction = UIAlertAction(title: "Save", style: .Default) { action -> Void in
let text = (firstAlert.textFields?[0] as UITextField).text
if text != nil && text!.characters.count>0 {
self.performSegueWithIdentifier("saveSegue",sender: self)
}
....other codes....
}

I have not test the code, hopefully it will work. Post a comment if there is any error.

Elegant way to check if UITextField is empty

How about extending UITextField

extension UITextField {

var isEmpty: Bool {
if let text = textField.text, !text.isEmpty {
return false
}
return true
}
}

so then…

if myTextField.isEmpty {
}

Empty text validation on multiple textfields inside alert controller

Try setting the delegate of each textField as the viewCobtroller where you're presenting the alert, i.e.

textField.delegate = self

Conform the ViewController to UITextFieldDelegate protocol,

class ViewController: UIViewController, UITextFieldDelegate {

Implemennt the relevant UITextFieldDelegate methods, Example:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let text = (textField.text as? NSString)?.replacingCharacters(in: range, with: string), !text.isEmpty {
submitAction.isEnabled = true
} else {
submitAction.isEnabled = false
}
return true
}

Edit:

You need to keep the reference to all the textFields so you can check the text in all of them to enable/disable the submitAction, i.e.

var textField1: UITextField?
var textField2: UITextField?
var textField3: UITextField?
var textField4: UITextField?

Set each of the textFields while adding to the UIAlertController, i.e.

let ac = UIAlertController(title: "Enter Custom Specifications", message: nil, preferredStyle: .alert)
ac.addTextField { (textField : UITextField!) -> Void in
textField.delegate = self
textField.placeholder = "Material Name"
self.textField1 = textField
}
ac.addTextField { (textField : UITextField!) -> Void in
textField.delegate = self
textField.keyboardType = UIKeyboardType.decimalPad
self.textField2 = textField
}
ac.addTextField { (textField : UITextField!) -> Void in
textField.delegate = self
textField.keyboardType = UIKeyboardType.decimalPad
self.textField3 = textField
}
ac.addTextField { (textField : UITextField!) -> Void in
textField.delegate = self
textField.keyboardType = UIKeyboardType.decimalPad
self.textField4 = textField
}

Call validate() everytime there is a change in any of the textFields, i.e.

func textFieldDidEndEditing(_ textField: UITextField) {
self.validate()
}

func validate() {
let text1 = self.textField1?.text ?? ""
let text2 = self.textField2?.text ?? ""
let text3 = self.textField3?.text ?? ""
let text4 = self.textField4?.text ?? ""

if !text1.isEmpty && !text2.isEmpty && !text3.isEmpty && !text4.isEmpty {
submitAction.isEnabled = true
} else {
submitAction.isEnabled = false
}
}

How to check if a text field is empty or not in swift

Simply comparing the textfield object to the empty string "" is not the right way to go about this. You have to compare the textfield's text property, as it is a compatible type and holds the information you are looking for.

@IBAction func Button(sender: AnyObject) {
if textField1.text == "" || textField2.text == "" {
// either textfield 1 or 2's text is empty
}
}

Swift 2.0:

Guard:

guard let text = descriptionLabel.text where !text.isEmpty else {
return
}
text.characters.count //do something if it's not empty

if:

if let text = descriptionLabel.text where !text.isEmpty
{
//do something if it's not empty
text.characters.count
}

Swift 3.0:

Guard:

guard let text = descriptionLabel.text, !text.isEmpty else {
return
}
text.characters.count //do something if it's not empty

if:

if let text = descriptionLabel.text, !text.isEmpty
{
//do something if it's not empty
text.characters.count
}

Check if if a text field from a collection of UITextFields is empty

You've set it up perfectly -- since you're already returning an optional UITextField?, if there aren't any empty text fields, return nil:

func findEmptyField() -> UITextField? {
for field in fieldsCollection {
if field.text.isEmpty {
return field
}
}
return nil
}

When calling it, note that you'll get an optional value back. Unwrap it with optional binding:

if let emptyField = findEmptyField() {
// focus emptyField or give a message
} else {
// all fields filled, ok to continue
}

Textfield is even empty but not considering as empty in Swift

Swift 5.2

A more elegant way to do it would be to create an extension on UITextField

extension UITextField {
var isEmpty: Bool {
if let text = self.text, !text.isEmpty {
return false
} else {
return true
}
}
}

And then you check like this:

if genderTextField.isEmpty || weightTextField.isEmpty || heightTextField.isEmpty {
showAlert()
} else {
// do something else
}

UITEXTFIELD input data to alert box ok clicked

I think your code is fine, only need to do a little changes.You need to return Combined string from this method.

Update below method.

func getvalueoftextfield() -> String {
let UserDestination: String = Choose_Destination.text!
print(UserDestination)

let UserDenomination: String = Choose_Denomination.text!
print(UserDenomination)

let UserEnteredDenomination: String = manual_denominaton_textfield.text!
print(UserEnteredDenomination)

let UserEmail: String = Email_textfield.text!
print(UserEmail)

let UserEnteredEmailConfirm: String = confirm_email_validation.text!
print(UserEnteredEmailConfirm)

let UserEnteredReceiversName: String = receivers_name_textfirld.text!
print(UserEnteredReceiversName)

let UserEnteredSendersName: String = senders_name_textfield.text!
print(UserEnteredSendersName)

let UserMessage: String = message_textView.text!
print(UserMessage)

let datacombined = String(format: "%@\n%@\n%@\n%@\n%@\n%@\n%@\n%@", UserDestination, UserDenomination, UserEnteredDenomination, UserEmail, UserEnteredEmailConfirm, UserEnteredReceiversName, UserEnteredSendersName, UserMessage
)

return datacombined
}

Show UIAlertController like this.

alert.addAction(UIAlertAction(title: "Agree", style: UIAlertActionStyle.default, handler: self.getvalueoftextfield()))

OR

let alertController = UIAlertController(title: AppName, message: self.getvalueoftextfield(), preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in

}

alertController.addAction(OKAction)
self.navigationController?.present(alertController, animated: true, completion: nil)


Related Topics



Leave a reply



Submit