When a user registers I need the email field to detect whether or not the field has a valid email in it (must have the @ symbol). How do I make the text field require this character in Swift? Such as Twitters signup.
答案 0 :(得分:1)
At first you need to use NSNotification to monitor the user's input. Red hint keeps showing
until user input some string likexxxx@xxx.com
, the hint goes off.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var alertLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector:"textFieldChanged:", name: UITextFieldTextDidChangeNotification, object: emailTextField)
// Do any additional setup after loading the view, typically from a nib.
}
func textFieldChanged(sender:AnyObject) {
var inputText = emailTextField.text
var isValid = NSPredicate(format: "SELF MATCHES %@", "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}").evaluateWithObject(inputText)
if(isValid == false){
alertLabel.backgroundColor = UIColor.redColor()
alertLabel.text = "Not a valid email address"
}else {
alertLabel.backgroundColor = UIColor.whiteColor()
alertLabel.text = ""
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 1 :(得分:0)
I used textfield "Editing did End" method for validation when leave textfield.
-(BOOL)NSStringIsValidEmail:(NSString *)checkString
{
BOOL stricterFilter = YES;
NSString *stricterFilterString = @"[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}";
NSString *laxString = @".+@([A-Za-z0-9]+\\.)+[A-Za-z]{2}[A-Za-z]*";
NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:checkString];
}
-(IBAction)emailValidation:(id)sender
{
if ([self NSStringIsValidEmail:self.emailTextField.text]) {
NSLog(@"Successful= login");
}
else{
UIAlertView *alrt=[[UIAlertView alloc] initWithTitle:@"Wrong Email" message:@"Please check your email " delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alrt show];
}
}
//Swift code
@IBAction func emailValidation(sender: AnyObject) {
if NSStringIsValidEmail(emailTextField.text) == true {
println("Valid")
//valid
}
else{
println(" Not Valid")
//invalid
}
}
func NSStringIsValidEmail(checkString: NSString) ->Bool
{
var stricterFilter = true
var stricterFilterString = "[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}"
var laxString = ".+@([A-Za-z0-9]+\\.)+[A-Za-z]{2}[A-Za-z]*"
var emailRegex = stricterFilter ? stricterFilterString : laxString
var emailTest = NSPredicate(format:"SELF MATCHES %@" ,emailRegex)
return emailTest.evaluateWithObject(checkString)
}