Setting validations on textfields - iphone

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

Related

How can I check that email address has been entered perfeclty in UITextfiled [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Email validation on textField in iPhone sdk
I have an app in which I want to get the user's email address as input. I want to check that the user has entered email address properly; like # should be in the text in the field. How can I do this?
textField.text=#"ali#hotmail.com"
If the text box has this value then OK otherwise it should alert that email address should be correct
You can use regExp validation, like this function
-(BOOL) isValidEmail:(NSString *)checkString
{
checkString = [checkString lowercaseString];
BOOL stricterFilter = 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 = stricterFilter ? stricterFilterString : laxString;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
return [emailTest evaluateWithObject:checkString];
}
use it like this
if([self isValidEmail:textField.text])
//Valid
else
//Not valid, do the alert
You can use below method :-
- (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];
}
The method will return TRUE if input is in correct format otherwise FALSE
Try this
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:m_CtrlTxtFld_Email.text] != YES && [m_CtrlTxtFld_Email.text length]!=0)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Please enter valid email address" message:#"" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
-(BOOL)isValidEmaill:(NSString*)in_EmailId
{
if( (0 != [in_EmailId rangeOfString:#"#"].length) && (0 != [in_EmailId rangeOfString:#"."].length) )
{
NSMutableCharacterSet *invalidCharSet = [[[[NSCharacterSet alphanumericCharacterSet] invertedSet]mutableCopy]autorelease];
[invalidCharSet removeCharactersInString:#"_-"];
NSRange range1 = [in_EmailId rangeOfString:#"#" options:NSCaseInsensitiveSearch];
// If username part contains any character other than "." "_" "-"
NSString *usernamePart = [in_EmailId substringToIndex:range1.location];
NSArray *stringsArray1 = [usernamePart componentsSeparatedByString:#"."];
for (NSString *string in stringsArray1) {
NSRange rangeOfInavlidChars=[string rangeOfCharacterFromSet: invalidCharSet];
if(rangeOfInavlidChars.length !=0 || [string isEqualToString:#""])
return NO;
}
NSString *domainPart = [in_EmailId substringFromIndex:range1.location+1];
NSArray *stringsArray2 = [domainPart componentsSeparatedByString:#"."];
for (NSString *string in stringsArray2) {
NSRange rangeOfInavlidChars=[string rangeOfCharacterFromSet:invalidCharSet];
if(rangeOfInavlidChars.length !=0 || [string isEqualToString:#""])
return NO;
}
return YES;
}
else // no '#' or '.' present
{
//[mEmailAddrTextField becomeFirstResponder];
return NO;
}
}

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

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.

how to validate textfield that allows . only once with in the textfield

I have 4 text fields in my application.
I validate my textfields as textfield allow 0,1,...9 and .,for that i write code as fallows
- (IBAction) textfield:(id)sender {
if ([textfield.text length] > 0) {
if ([textfield.text length] > 10){
textfield.text = [textfield.text substringWithRange:NSMakeRange(0, 10)];
}
else {
//retrieve last character input from texfield
int I01 = [homevalue.text length];
int Char01 = [homevalue.text characterAtIndex:I01-1];
//check and accept input if last character is a number from 0 to 9
if ( (Char01 < 46) || (Char01 > 57) || (Char01 == 47) ) {
if (I01 == 1) {
textfield.text = nil;
}
else {
textfield.text = [homevalue.text substringWithRange:NSMakeRange(0, I01-1)];
}
}
}
}
}
It works fine, Now i need to validate that . allows only once with in the textfield.
eg: 123.45
According to my code if i place again . it is allowed.
eg:123.45.678
But it wont allowed once i place . ,that textfield wont allowed.
ed:123.45678.
How can i done this,
can any one pls help me.
Thank u in advance.
Try this predicate for texts that start with a number like "23.67"
NSString *decimalRegex = #"[0-9]+([.]([0-9]+)?)?"; // #"[0-9]+[.][0-9]+";
NSPredicate *decimalTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", decimalRegex];
BOOL isValidDecimal = [decimalTest evaluateWithObject:[textField text]];
If you want to allow "." at the fist place like ".95" use the following regex,
NSString *decimalRegex = #"[0-9]*([.]([0-9]+)?)?"; //#"[0-9]*[.][0-9]+";
Your code should look like this,
- (IBAction)textfield:(id)sender {
int textLength = [[textfield text] length];
if (textLength > 0) {
NSString *decimalRegex = #"[0-9]+([.]([0-9]+)?)?"; //#"[0-9]+[.][0-9]+";
NSPredicate *decimalTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", decimalRegex];
BOOL isValidDecimal = [decimalTest evaluateWithObject:[textField text]];
if (!isValidDecimal) {
NSString *text = [[textField text] substringToIndex:textLength - 1];
[textfield setText:text]
}
}
}
I guess this should work! Give it a try!
Well you can use this method
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet options:(NSStringCompareOptions)mask range:(NSRange)aRange
on textfield.text as its a NSString only