How to have a firstname validation in iOS swift4?

text field validation in swift 4
username regex swift
allow only alphabets in uitextfield swift
username and password validation in swift
first name validation rules
swift regex
swift form validation
uitextfield validation error message swift

I have a first name validation to be done in swift4 which is in a UITextField. The thing is that:

  1. The Firstname should start with a letter and end with a letter,
  2. No trailing and leading whitespace.
  3. It can have spaces between them, can contain dot.
  4. should be between 7 and 18 characters.

Currently i am having the following validation in the UITextField

public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let STRING_ACCEPTABLE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    switch textField {
    case firstName:
        print("firstname")
        if string == " " {
            return false
        } else {
            let cs = NSCharacterSet(charactersIn: STRING_ACCEPTABLE_CHARACTERS).inverted
            let filtered = string.components(separatedBy: cs).joined(separator: "")
            return (string == filtered)
        }
    }
    return true
}

Any idea how to implement the following conditions. Right now I am disabling the space and only accepts the alphabets.

Any help will be very much appreciated

You can use this func for short and clean way

func isValid(testStr:String) -> Bool {
    guard testStr.count > 7, testStr.count < 18 else { return false }

    let predicateTest = NSPredicate(format: "SELF MATCHES %@", "^(([^ ]?)(^[a-zA-Z].*[a-zA-Z]$)([^ ]?))$")
    return predicateTest.evaluate(with: testStr)
}

Test cases

isValid(testStr: " MyNameIsDahiya") // Invalid, leading space
isValid(testStr: "MyNameIsDahiya ") // Invalid, trailing space
isValid(testStr: " MyNameIsDahiya ") // Invalid, leading & trailing space
isValid(testStr: "1MyNameIsDahiya") // Invalid, Leading num
isValid(testStr: "MyNameIsDahiya1") // Invalid, trailing num
isValid(testStr: "1MyNameIsDahiya1") // Invalid, leading & trailing num
isValid(testStr: "MyName") // Invalid, length below 7
isValid(testStr: "MyNameIsDahiyaBlahhblahh") // Invalid, length above 18

isValid(testStr: "MyNameIsDahiya") // Valid,
isValid(testStr: "Mr. Dahiya") // Valid,

Playground Test

Edit

Try this below regex:

(?mi)^[a-z](?!(?:.*\.){2})(?!(?:.* ){2})(?!.*\.[a-z])[a-z. ]{5,16}[a-z]$

It will validate all the conditions and length also.

How to have a firstname validation in iOS swift4?, I have a first name validation to be done in swift4 which is in a UITextField. The thing is that: The Firstname should start with a letter and end with a letter, No� Local Receipt Validation for iOS in Swift From Start to Finish Local receipt validation in Swift doesn’t seem to be widely written about. I’ve been able to find snippets of code scattered across the Internet, but nothing that brought everything together in one spot so that I could wrap my head around the whole process.

You can use regex to validate First name with your conditions.

I'm not an expert in regex, but here you can see an example

^[a-zA-Z](?:[a-zA-Z\.\s][^\n]*)[a-zA-Z]$

This regex will return you full matches. You can check, if any matches returned string is valid.

Link with example of usage regex in Swift.

Number of string characters you can check using Swift, like:

if string.count > 7 && string.count < 18 {
    //String valid
}

Generic way to validate textField inputs in Swift 4.2, To make generic validation class i'm going to use variadic Using .xcconfig files to store various SDK keys and IDs inside Xcode Project. Simple phone number validation in swift ios 8 , Using this function you can easily check phone number . Also have some example for this using NSPredicate etc . you can see lots of method for number validation. But I made this sort method

You can check the two conditions when you are taking the value from UITextField which are:

  1. Firstname should start and end with a letter
  2. Trimming whitespaces at the end.

And the rest conditions can be done inside shouldChangeCharactersInRange like below:

let STRING_ACCEPTABLE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz. "
    switch textField {
    case firstName:
        print("firstname")
        //Condition for always accepting backcspaces
        if string == "" {
            return true
        }
        //Condition for restricting space at the begining
        else if textField.text?.count == 0 && string == " " {
            return false
        }
        //Condition for restricing user from entering more than 18 letters
        else if (textField.text?.count)! > 17 {
          return false
        }
        //Condition for only accepting the alphabets.
        else {
            let cs = NSCharacterSet(charactersIn: STRING_ACCEPTABLE_CHARACTERS).inverted
            let filtered = string.components(separatedBy: cs).joined(separator: "")
            return (string == filtered)
        }

For checking the minimum number of letters, trimming whitespaces at the end and starting and ending with a letter with below conditions inside a Button's click or something equivalent to it:

//Trimming whitespaces at the end
let firstname = firstName.text?.trimmingCharacters(in: .whitespaces)

let letters = NSCharacterSet.letters

let prefix = String((firstname?.first)!)
let suffix = String((firstname?.last)!)

//Checking if First Character is letter
if let _ = prefix.rangeOfCharacter(from: letters) {
    print("letters found")
} else {
    print("letters not found")
}

//Checking if Last Character is letter
if let _ = suffix.rangeOfCharacter(from: letters) {
    print("letters found")
} else {
    print("letters not found")
}

Hope this helps.

Regular Expressions Tutorial: Getting Started, Open the iRegex starter project in Xcode and run it. To create the regular expression to validate the first name, you first match from the� This is the straightforward way to do validation. With shouldChangeCharactersInRange there is a risk to get stuck with a big number of variations: user pastes a text, user enters in the mid of text or deletes in the mid of text - they all have to be taken into account. But with textFieldDidChange we just have the end result and can validate it

Five Simple Tips to Make User Friendly Forms on iOS, Even though forms aren't difficult to implement on iOS, they can be frustrating to Swift 4 Xcode 9 iOS 11 import UIKit class ViewController: UIViewController { // MARK: - Properties @IBOutlet var firstNameTextField: UITextField! We only make the email text field the first responder if validation succeeds. Here I have created a simple app on the App Store. I will create subscriptions for weekly, monthly, quarterly and yearly based subscriptions. Let’s set detail for each subscription with the price. e.g. $0.99/week $1.99/month $4.99/quarter $9.99/year. Once we have list of all products we will purchase them one by one on app side.

Email Address Validation in Swift, Thank you! Post navigation. Previous Previous post: Xcode Code Snippets Library. Creating and� you have to adjust the allowed lenght of the second string if you add a 1st group that does not include space and dash (since that group contributs an additional character). with \p{L} you allow any kind of letter from any language (which is good); otherwise use [a-zA-z] if just want to allow the regular (ASCII) alphabet.

How To Validate Textfield Using Swift 2.0 in iOS, Objective:- Make a registration form with apply all required validation. Create a new @IBOutlet weak var firstName: UITextField! @IBOutlet� Drop in user input validation for your iOS apps. Contribute to adamwaite/Validator development by creating an account on GitHub.

Comments
  • Could you please also think about non-English names that contain other characters? For example "María" or "François"? a-z characters are not the only letters that exist. I am not saying how will your validation fail for asian name. My first name is even shorter than 7 characters.
  • will "Mr Dahiya" will be valid?
  • @ElizabethMoly Yeah, check last option.
  • Thanks a lot. is it possible to accept only single space between them? because "mr(6 white space in between)y" is also getting accepted
  • Thanks a lot I will check and let you know
  • it sounds nice but i would like to validate when the user stops editing and moves to next uitextfield . How to achieve that?
  • Do that in didEndEditing then!