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.
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.
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.
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
}
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With