How to check if UITextField's text is valid email? - iphone

I have a view controller with 3 UITextFields (username, email, and password).
I need a method that checks first, if all fields have text in them, then check if the email's textfield is a valid email, perhaps by checking if it has an # sign in it. Can anyone help with this?

Following code is use for the checking the validation of the email id using the Regex(Regular expresion).
(BOOL) validateEmail: (NSString *) candidate {
NSString *emailRegex = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex]; // return 0;
return [emailTest evaluateWithObject:candidate];
}

This will check a UITextField for a proper email.
Add this method to the textFields delegate then check if the characters it is about to change should be added or not.
Return YES or NO depending on the text fields current text compared to a valid email address:
#define ALPHA #"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
#define NUMERIC #"1234567890"
#define ALPHA_NUMERIC ALPHA NUMERIC
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *unacceptedInput = nil;
if ([[textField.text componentsSeparatedByString:#"#"] count] > 1) {
unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:#".-"]] invertedSet];
} else {
unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:#".!#$%&'*+-/=?^_`{|}~#"]] invertedSet];
}
return ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] <= 1);
}
To check if a text field is empty or not just use if (myTextField.text.length > 0) {} anywhere in your view controller.

I have used Mimit's solution but modified the emailRegex to allow for longer names such as museum. So the last curly brackets now says {2, 6} not {2, 4}. And I tested it with the longer name and it works. Thanks Mimit for the easy solution.
-(BOOL) validateEmail: (NSString *) candidate {
NSString *emailRegex = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex]; // return 0;
return [emailTest evaluateWithObject:candidate];
}

try this:-
if(![emailTextField.text isEqualToString:#""] && ![userNameTextField.text isEqualToString:#""] && ![passwordTextField.text isEqualToString:#""])
{
NSString *emailRegEx = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegEx];
//Valid email address
if ([emailTest evaluateWithObject:emailTextField.text] == YES)
{
}
else
{
//not valid email address
}
}
else
{
//any of the text field is empty
}

If you are targeting iOS 4.0 or greater, you might also consider NSRegularExpression and do more nuanced checking of the UITextField contents along the lines of this, for example.

Related

Setting validations on textfields

I m doing a registration form and if any of the textfield is left empty then I want to validate it .But I dont want to display a regular UIAlertView when textfield is empty.
Can I display any redcoloured star marked or anything else beside particular textField?
How can I validate to check for emailId pattern?
You can set text with red color in your textField
if ([yourTextField.text isEqualToString:#""])
{
yourTextField.textColor=[UIColor redColor];
yourTextField.text=#"Value Required";
}
set delegate of your textField in .h file
<UITextFieldDelegate>
and in textFieldDidBeginEditing you can change your textField color
If you are setting * in your textField then do this
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
if ([textField.text isEqualToString:#"*"])
{
textField.text=#"";
textField.textColor=[UIColor blackColor];
}
}
Or you can make a label beside your textField and hide it initially and show when ever you needed.
Validation for email
- (BOOL)isValidEmailId:(NSString*)email
{
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:email];
}
Validation for email field:
- (BOOL)EmailValidationL:(NSString *)email
{
NSString *emailRegEx =#"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
#"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
#"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")#(?:(?:[a-z0-9](?:[a-"
#"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
#"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
#"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
#"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegEx];
a= [regExPredicate evaluateWithObject:email];
return a;
}
And for checking it do like below:
if (![self EmailValidationL:emailtxt.text])
{
mailAlert =[[UIAlertView alloc]initWithTitle:#"Error"
message:#"Email Field Is Not Valid"
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:#"OK",nil];
[mailAlert show];
[mailAlert release];
}
Yes you can show a red coloured image or label with * text on it and you can hide and show it like wise .
To validate email you can use the following code
+(BOOL) validateEmail: (NSString *) email
{
NSString *emailRegex = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
BOOL isValid = [emailTest evaluateWithObject:email];
return isValid;
}
You can try this:
First, take simple label in XIB with simple text & color:
-(void)DidLoad
{
-----
lbl.hidden = YES;
-----
}
Attributes:
text = "* email invalid"
color = "red"
Or whatever you like.
'textDidEndEditing' method.
- (void)textFieldDidEndEditing:(UITextField *)textField
{
if(textField == txtEmail)
{
if(![txtEmail.text isEqualToString:#""])
{
bool chk = [self validateEmail:txtEmail.text];
if(!chk)
{
lbl.hidden = NO;
lbl.text = #"email invalid";
}
else
lbl.hidden = YES;
}
else
{
lbl.hidden = NO;
lbl.text = #"* required";
}
}
}
Email Validation
+(BOOL) validateEmail: (NSString *) email
{
NSString *emailRegex = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
BOOL isValid = [emailTest evaluateWithObject:email];
return isValid;
}
Ok so you get many solution for Email.
so lets go for star. You may have many way for this let me give two of them
Add hidden UIImageView where you want to show start and make is visible when use left it empty
use [UIView addSubView:UIImageView] to show start when you want to show.
If u want to show normal * in red color you can use UILabel instead of UIImageView.
I use following to validate email:
NSString *emailRegex = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
if(![emailTest evaluateWithObject:txtMail.text])
{
//Your code if wrong email
}
All the best....
Firstly Shashank Kulshrestha has given nice answer of validating email . Now if you want show some thing for indicating the invalid or empty input do following to that text field. It will show red edges.
1.Add QuartzCore framework.
2.Import #import
3.add following code :
if (textfield==empty || invalid)
{
textField.layer.cornerRadius=8.0f;
textField.layer.masksToBounds=YES;
textField.layer.borderColor=[[UIColor redColor]CGColor];
textField.layer.borderWidth= 1.0f;
}

NSString value validation in iOS

This simple validation method for NSString makes trouble.
I have an NSString value and I want to validate the string, i.e, if the string contains only 'a to z' (or) 'A to Z' (or) '1 to 9' (or) '#,!,&' then the string is valid. If the string contains any other values then this the NSString is invalid, how can i validate this..?
As example:
Valid:
NSString *str="aHrt#2"; // something like this
Invalid:
NSString *str="..gS$"; // Like this
Try using character sets:
NSMutableCharacterSet *set = [NSMutableCharacterSet characterSetWithCharactersInString:#"#!&"];
[set formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
if ([string rangeOfCharacterFromSet:[set invertedSet]].location == NSNotFound) {
// contains a-z, A-Z, 0-9 and &#! only - valid
} else {
// invalid
}
I would do something using stringByTrimmingCharactersInSet
Create an NSCharacterSet containing all valid characters, then trim those characters from the test string, if the string is now empty it is valid, if there are any characters left over, it is invalid
NSCharacterSet *validCharacters = [NSCharacterSet characterSetWithCharactersInString:#"myvalidchars"];
NSString *trimmedString = [testString stringByTrimmingCharactersInSet:validCharachters];
BOOL valid = [trimmedString length] == 0;
Edit:
If you want to control the characters that can be entered into a text field, use textField:shouldChangeCharactersInRange:replacementString: in UITextFieldDelegate
here the testString variable becomes the proposed string and you return YES if there are no invalid characters
The NSPredicate class is what you want
More info about predicate programming. Basically you want "self matches" (your regular expression). After that you can use the evaluateWithObject: method.
EDIT Easier way: (nevermind, as I am editing it wattson posted what I was going to)
You can use the class NSRegularExpression to do this.
https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html
You can also use NSRegularExpression to search your NSString, if it contains only the valid characters (or vice versa).
More info:
Search through NSString using Regular Expression
Use regular expression to find/replace substring in NSString
- (BOOL)validation:(NSString *)string
{
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:#"1234567890abcdefghik"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
return ([string isEqualToString:filtered]);
}
In your button action:
-(IBAction)ButtonPress{
if ([self validation:activity.text]) {
NSLog(#"Macth here");
}
else {
NSLog(#"Not Match here");
}
}
Replace this "1234567890abcdefghik" with your letters with which you want to match
+(BOOL) validateString: (NSString *) string
{
NSString *regex = #"[A-Z0-9a-z#!&]";
NSPredicate *test = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
BOOL isValid = [test evaluateWithObject:string];
return isValid;
}
You can simply do it using NSMutableCharacterSet
NSMutableCharacterSet *charactersToKeep = [NSMutableCharacterSet alphanumericCharacterSet];
[charactersToKeep addCharactersInString:#"#?!"];
NSCharacterSet *charactersToRemove = [charactersToKeep invertedSet]
NSString *trimmed = [ str componentsSeparatedByCharactersInSet:charactersToRemove];
if([trimmed length] != 0)
{
//invalid string
}
Reference NSCharacterSet
You can use regex. If every thing fails use brute force like
unichar c[yourString.length];
NSRange raneg={0,2};
[yourString getCharacters:c range:raneg];
// now in for loop
for(int i=0;i<yourString.length;i++)
{
if((c[i]>='A'&&c[i]<='Z')&&(c[i]=='#'||c[i]=='!'||c[i]=='&'))
{
//not the best or most efficient way but will work till you write your regex:P
}
}

Alter reg-ex for email Validation on iphone

I am trying to validate email using reg-ex. here is the code...
+ (BOOL) stringIsValidEmail:(NSString *)checkString;
{
NSString *emailRegEx =
#"(?:[a-zA-Z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
#"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
#"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")#(?:(?:[a-z0-9](?:[a-"
#"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
#"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
#"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
#"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegEx];
return [emailTest evaluateWithObject:checkString];
}
now I don't have much knowledge about regex but this accepts a#a.c as a valid email. But this should not be the case and at least two characters should be required at the end. What paramater do I need to change in this so it returns false. I have hit and tried but that didn't work. Thanks for your help.
Too much symbols, you can try this
- (BOOL) IsValidEmail:(NSString *)checkString {
BOOL sticterFilter = YES;
NSString *stricterFilterString = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSString *laxString = #".+#.+\\.[A-Za-z]{2}[A-Za-z]*";
NSString *emailRegex = sticterFilter ? stricterFilterString : laxString;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
return [emailTest evaluateWithObject:checkString];
}
Try using this as regex
NSString *emailRegex = #"[A-Z0-9a-z._]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
the {2,4} especially validates that the ending characters should be alphabets and more than two in count

TextField Validation With Regular Expression

I need help with code that looks at a textfield make sure it starts with either a (+ or -) then has 3 integers after it.
So valid data looks like +234 or -888
So I have started this code but there are 2 problems with it
It correctly validates that only 4 characters are entered. But for some reason you have to take focus off the textfield in order for the Done button on the keyboard to fire and hide the keyboard. If I only put less than 4 characters in the textfield then the Done button works fine. But I dont want the user to enter anything but 4 characters and then press Done and hide the keyboard. Thats the first problem....
I am not familar with regular expressions and how to use them in iphone. So I need to add to this code regular expression for the above requirement.
-(BOOL)textField:(UITextField*)textFieldshouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
return !([newString length] > 4);
}
//Done button to hide the keyboard
-(IBAction)Done:(id)sender
{
}
I am not sure how you'd like to handle user input and feedback. First I'll show a simple way to keep the user in the editing mode of the textField if her input is not valid.
First of all two delegate methods:
- (BOOL)textFieldShouldReturn:(UITextField *)aTextField
{
[aTextField resignFirstResponder];
return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)aTextField
{
return [self validateInputWithString:aTextField.text];
}
The testing method, which just returns YES or NO whether the input is valid or not:
- (BOOL)validateInputWithString:(NSString *)aString
{
NSString * const regularExpression = #"^([+-]{1})([0-9]{3})$";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regularExpression
options:NSRegularExpressionCaseInsensitive
error:&error];
if (error) {
NSLog(#"error %#", error);
}
NSUInteger numberOfMatches = [regex numberOfMatchesInString:aString
options:0
range:NSMakeRange(0, [aString length])];
return numberOfMatches > 0;
}
That's it. However I'd recommend showing some live status to the user whether his input is ok or not. Add the following notifcation, for example in your viewDidLoad method:
- (void)viewDidLoad
{
// ...
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(validateInputCallback:)
name:#"UITextFieldTextDidChangeNotification"
object:nil];
}
- (void)validateInputCallback:(id)sender
{
if ([self validateInputWithString:textField.text]) {
// For example turn a label green and let it say: "OK"
} else {
// For example turn a label red and let it say: "Allowed: + or minus followed by exactly three digits"
}
}
Finally: If you need to access the capture groups (+ or - and the number) of the regular expression the following code will help:
// ... reg ex creation ...
NSArray *matches = [regex matchesInString:aString
options:0
range:NSMakeRange(0, [aString length])];
for (NSTextCheckingResult *match in matches) {
for (int i = 0; i < [match numberOfRanges]; i++) {
NSLog(#"range %d: %d %d", i, [match rangeAtIndex:i].location, [match rangeAtIndex:i].length);
NSLog(#"substring %d: %#", i, [aString substringWithRange:[match rangeAtIndex:i]]);
}
}
Validate Email id or Phone number using Regular Expression
Ddelegate methods:
- (BOOL)textFieldShouldReturn:(UITextField *)aTextField
{
[aTextField resignFirstResponder];
return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)aTextField
{
return [self validateEmail:aTextField.text]; // Change validateEmail to validatePhone for phone validation.
}
Returns YES or NO whether the input is valid or not:
- (BOOL) validateEmail: (NSString *) candidate {
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:candidate];
}
- (BOOL) validatePhone: (NSString *) candidate {
NSString *phoneRegex = #"^+(?:[0-9] ?){6,14}[0-9]$";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", phoneRegex];
return [phoneTest evaluateWithObject:candidate];
}
Use UIPickerView instead
I am departing from the question title but IMHO considering what you need, it may be better to use UIPickerView to have a "spinning-wheel" type of entry, like you do in the Clock app when setting alarm. It can start at "+000" and user can tumble some of the four wheels ([+-]. [0-9], [0-9], [0-9]) as needed
Implement the -textField:shouldChangeCharactersInRange:replacementString in your UITextFieldDelegate and use NSRegularExpression to validate the changes.

Email Validation iPhone SDK

Assuming I have created IBOutlet UITextField *emailValidate;
And the empty method
-(IBAction)checkEmail:(id)sender {
// Add email validation code here.
}
And linked the File Owner file to the TextField, what code would I have to insert in the method to validate an email adress? checking that only one '#' is included, and only one '.' is included?
Use the function below...
+(BOOL) validateEmail: (NSString *) email
{
NSString *emailRegex = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
BOOL isValid = [emailTest evaluateWithObject:email];
return isValid;
}
In my case I use a regex found at this blogpost:
NSString *emailRegEx =
#"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
#"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
#"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")#(?:(?:[a-z0-9](?:[a-"
#"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
#"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
#"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
#"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
You can determine if there is exactly one "#" by splitting the string on '#' and checking for 2 pieces.
int numberOfAtPieces = [[emailValidate.text componentsSeparatedByString:#"#"] count];
if ( numberOfAtPicess != 2 ) { // show error alert }
else { // let it through }
You can get set of code from the following link . Hope this may helpful
I've used the solution shared by Macarse (the big regexp) for a few weeks with success, but I suddenly ran into a problematic case. It does not pass the test with "test1_iPhone#neywen.net" for instance.
So I chose to go back to the simpler solution provided by S P Varma (the small and simple regexp).
You could call the following method on the text of the UITextField:
- (BOOL)validateEmail:(NSString *)candidate {
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:candidate];
}
Please adapt the emailRegex regular expression to your needs.