Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any way to make a Text field entry must be email? (in xcode)

I want to make a user login form and it needs to use emails not just usernames. Is there any way i can make a alert pop up if it is not an email? btw All of this is in xcode.

like image 843
inVINCEable Avatar asked Aug 19 '11 15:08

inVINCEable


People also ask

How do you make a text field non editable in Swift?

You should have a Bool Variable. Set it to 'false' then when the button is pressed you toggle it to 'true'. Depending on its state just run to different methods which essentially allows you to edit or not.

What is a secure text field?

A SecureField uses a binding to a string value, and a closure that executes when the user commits their edits, such as by pressing the Return key. The field updates the bound string on every keystroke or other edit, so you can read its value at any time from another control, such as a Done button.


2 Answers

There is a way using NSPredicate and regular expression:

- (BOOL)validateEmail:(NSString *)emailStr {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:emailStr];
}

Then, you can display an alert if email address is wrong:

- (void)checkEmailAndDisplayAlert {
    if(![self validateEmail:[aTextField text]]) {
        // user entered invalid email address
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Enter a valid email address." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        [alert release];
    } else {
        // user entered valid email address
    }
}
like image 168
akashivskyy Avatar answered Nov 05 '22 22:11

akashivskyy


To keep this post updated with modern code, I thought it would be nice to post the swift answer based off of akashivskyy's original objective-c answer

// MARK: Validate
func isValidEmail(email2Test:String) -> Bool {
    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
    let range = email2Test.rangeOfString(emailRegEx, options:.RegularExpressionSearch)
    let result = range != nil ? true : false
    return result
}    
like image 34
inVINCEable Avatar answered Nov 05 '22 20:11

inVINCEable