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.
Related
When I tried matching the string with the regex '^(34|37)' it does not work even after giving the correct one. Can anyone please point out or guide me to what I am doing wrong?
This is my code:
NSPredicate *myTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", #"^(34|37)"];
if([myTest evaluateWithObject: #"378282246310005"]){
NSLog(#"match");
}
Your regex will not match the given string. That is ^(34|37) does not match 378282246310005. It matches the first two characters, but after that it fails because the string contains more characters, while your regex terminates.
You need to alter your regex to match the rest of the characters, even if you don't want to capture them. Try changing your regext to ^(34|37).*.
Make seprate method for matching regex as bool type. Then it will work.
like this
- (IBAction)tapValidatePhone:(id)sender
{
if(![self validateMobileNo:self.txtPhoneNo.text] )
{
NSLog(#"Mobile No. is not valid");
}
}
-(BOOL) validateMobileNo:(NSString *) paramMobleNo
{
NSString *phoneNoRegex = #"^(34|37)";
NSPredicate *phoneNoTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#",phoneNoRegex];
return [phoneNoTest evaluateWithObject:#"3435"];
}
it is not going in else condition.
Why not just use hasPrefix:
if([#"378282246310005" hasPrefix:#"34"] || [#"378282246310005" hasPrefix:#"37"])
{
NSLog(#"found it");
}
EDIT:
Using NSPredicate:
NSPredicate *myTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", #"^3(4|7)\\d+$"];
if([myTest evaluateWithObject: #"378282246310005"])
{
NSLog(#"match");
}
else
{
NSLog(#"notmatch");
}
Using NSRegularExpression:
NSError *error = nil;
NSString *testStr = #"348282246310005";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"^3(4|7)" options:NSRegularExpressionCaseInsensitive error:&error];
NSInteger matches = [regex numberOfMatchesInString:testStr options:NSMatchingReportCompletion range:NSMakeRange(0, [testStr length])];
if(matches > 0 )//[myTest evaluateWithObject: #"378282246310005"])
{
NSLog(#"match");
}
else
{
NSLog(#"notmatch");
}
BTW: (34|37) does not look 34 or 37 instead it seems 347 or 337 to me, since engine will pick 4|3 either 4 or 3.
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
I am using a NSPredicate to search numbers in the list using UISearchBar ,
it works in case of strings but does not work for an integer
I am using the following predicate
predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"%# contains[c] %d", #"number", [searchBar.text intValue]]];
[objectArray filterUsingPredicate:predicate];
[tableview reloadData];
FOR example if I type 1 then all the ones in the array must be listed, I have tried == it works only for the exact number if tried any work around for this any body?
Now I get an error if I use this method "Can't use in/contains operator with collection"
I think this predicate should work for you:
predicate = [NSPredicate predicateWithFormat:#"self.number.stringValue CONTAINS %#",searchBar.text];
After thinking about this, I'm not sure why self.number.stringValue works, but it did when I tested it (self.number is an int). Not sure why I can send stringValue to an int?
Predicates can be tricky to work with, so perhaps an alternative would work for you:
NSInteger index = 0;
while (index < objectArray.count)
{
NSString *currentString = [objectArray objectAtIndex:index];
if ([currentString rangeOfString:searchBar.text].length == 0)
{
[objectArray removeObjectAtIndex:index];
continue;
}
index++;
}
Here, any strings in your array that do not contain your searchBar text will be removed.
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.
Hi how can I validate email address, username, fullname and date of birth for my registration form inside an iphone application.
You can use NSPredicate with regular expressions in iPhone OS > 3.0 like so
- (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];
}
Another simple way of validating an email address is using the US2FormValidator framework.
Example:
US2ValidatorEmail *emailValidator = [US2ValidatorEmail alloc] init];
US2ConditionCollection *collection1 = [emailValidator checkConditions:#"example#example.com"];
// collection1 == nil, thus YES
US2ConditionCollection *collection2 = [emailValidator checkConditions:#"example#example."];
// collection2.length > 0, thus NO
US2ConditionCollection *collection3 = [emailValidator checkConditions:#"example"];
// collection3.length > 0, thus NO
BOOL isValid = [emailValidator checkConditions:#"example#example.com"] == nil;
// isValid == YES
You can simply use the US2ValidatorTextField instead of UITextField and connect to this US2ValidatorEmail. The text field will tell you what went wrong and if the user corrected the text.
The framework can be found on GitHub or Softpedia.
If you would like to only check phone numbers iOS also provides so called NSDataDetector's.
Usage like:
theTextView.dataDetectorTypes = UIDataDetectorTypePhoneNumber;
Read more about it here: http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSDataDetector_Class/Reference/Reference.html