iphone app Form validation - iphone

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

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;
}

Code working on Simulator, but not on iPhone?

I am stumped by this: I've tested the filter function of my app in the iPhone Simulator 4.3 and 5.0 and everything works, but on the iPhone the predicate gets me the wrong results. (I suspect it has something to do with the regex, but I don't see an error.)
if (!selectionDidChange)
return;
[matches release];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"meta LIKE[c] %#",
UniversalKeyword];
NSPredicate *regional = [NSPredicate predicateWithFormat:#"regional == NIL OR regional == NO OR "
#"(regional == YES AND title.%K != NIL)", CurrentLanguage];
NSPredicate *exclusive = (exclusiveUpgrade ? [NSPredicate predicateWithValue:YES] :
[NSPredicate predicateWithFormat:#"exclusive == NIL OR exclusive == NO"]);
NSMutableArray *predicates = [[[NSMutableArray alloc] initWithCapacity:5] autorelease];
for (int i = 0; i < L(keywords); i++)
{
int selection = [D(A(keywords, i), #"selection") intValue];
if (selection >= 0)
A_ADD(predicates, ([NSPredicate predicateWithFormat:#"meta MATCHES[c] %#",
S(S(#".*\\b", D(A(D(A(keywords, i), #"values"), selection), #"name")), #"\\b.*")]));
}
NSPredicate *compound = [NSCompoundPredicate andPredicateWithSubpredicates:predicates];
[predicates removeAllObjects];
[predicates addObject:predicate];
[predicates addObject:compound];
predicate = [NSCompoundPredicate andPredicateWithSubpredicates:A_NEW(regional, exclusive,
[NSCompoundPredicate orPredicateWithSubpredicates:predicates])];
matches = [[entries filteredArrayUsingPredicate:predicate] retain];
selectionDidChange = NO;
For clarification:
entries and keywords are arrays of dictionaries, although keywords is a bit more complex. Important is that each dictionary in entries contains a string named meta that can look something like this: "A, B, C, D". And if the user searches for "C", the regex should match. There are other criteria that don't seem to be the problem, since I checked the compiled predicate and it looks fine.
I should mention, the first part of the predicate (meta LIKE[c] %#) gives me the expected result on the iPhone as well.
I have some used convenience macros here: A_ADD = addObject:, D = objectForKey:, A = objectAtIndex:, A_NEW = arrayWithObjects:, L = count and S = stringByAppendingString:. (Yeah, I'm lazy :D )
What am I overlooking here?
Here are the key points in case anybody else has a similar problem:
There are no functional differences between NSPredicate on the iPhone and the corresponding implementation on the iOS Simulator.
If your app behaves differently on the actual device than on the Simulator, double-check file names and other strings for capitalization, like jmstone said.
If the problem persists, remove the app both from the Simulator and from the device. Xcode has many automatic behaviors, but it doesn't clean up anything on the Simulator or the device.

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

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.

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.
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
}
I did something like this in my app, where I validated that the email address field had 2 parts separated by the '#' symbol, and at least 2 parts separated by a '.' symbol. This does not check that it is a valid email address, but does make sure that it is in the correct format, at least. Code example:
// to validate email address, just checks for # and . separators
NSArray *validateAtSymbol = [[emailRegisterTextField text] componentsSeparatedByString:#"#"];
NSArray *validateDotSymbol = [[emailRegisterTextField text] componentsSeparatedByString:#"."];
// checks to make sure entries are good (email valid, username available, passwords enough chars, passwords match
if ([passwordRegisterTextField text].length >= 8 &&
[passwordRegisterTextField text].length > 0 &&
[[passwordRegisterTextField text] isEqual:[passwordVerifyRegisterTextField text]] &&
![currentUser.userExist boolValue] &&
![[emailRegisterTextField text] isEqualToString:#""] &&
([validateAtSymbol count] == 2) &&
([validateDotSymbol count] >= 2)) {
// get user input
NSString *inputEmail = [emailRegisterTextField text];
NSString *inputUsername = [userNameRegisterTextField text];
NSString *inputPassword = [passwordRegisterTextField text];
NSString *inputPasswordVerify = [passwordVerifyRegisterTextField text];
NSLog(#"inputEmail: %#",inputEmail);
NSLog(#"inputUsername: %#",inputUsername);
NSLog(#"inputPassword: %#",inputPassword);
NSLog(#"inputPasswordVerify: %#",inputPasswordVerify);
// attempt create
[currentUser createUser:inputEmail username:inputUsername password:inputPassword passwordVerify:inputPasswordVerify];
}
else {
NSLog(#"error");
[errorLabel setText:#"Invalid entry, please recheck"];
}
You can have an alert pop up if something is incorrect, but I chose to display a UILabel with the error message, since it seemed less jarring to the user. In the above code, I checked the format of the email address, the password length, and that the passwords (entered twice for verification) matched. If all of these tests were not passed, the app did not perform the action. You can choose which field you want to validate, of course...just figured I'd share my example.
This way works well for me.
1.check string has only one #
2.check at least has one . after #
2.with out any space after #
-(BOOL)checkEmailString :(NSString*)email{
//DLog(#"checkEmailString = %#",email);
BOOL emailFlg = NO;
NSArray *atArr = [email componentsSeparatedByString:#"#"];
//check with one #
if ([atArr count] == 2) {
NSArray *dotArr = [atArr[1] componentsSeparatedByString:#"."];
//check with at least one .
if ([dotArr count] >= 2) {
emailFlg = YES;
//all section can't be
for (int i = 0; i<[dotArr count]; i++) {
if ([dotArr[i] length] == 0 ||
[dotArr[i] rangeOfString:#" "].location != NSNotFound) {
emailFlg = NO;
}
}
}
}
return emailFlg;
}

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.