RegEx validation of techmahindra account - ios

I want to validate for textfield of email and wants to find out is it techmahindra email or not. How can I find it . I am attaching my code here.
Could any one suggest changes.
NSString * myString = # "#";
NSArray * myWords = [emailStr componentsSeparatedByString: myString];
NSString * str = [myWords objectAtIndex: 1];
if ([str isEqualToString: # "techmahindra.com"]) {
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];
} else
return NO;

Given that you have written code to extract the part of the string that follows the # symbol, you don't need regular expressions there. You can simply do a case-insensitive comparison, like this:
if (str != nil && [str compare:#"techmahindra.com" options:NSCaseInsensitiveSearch]) {
return [emailTest evaluateWithObject:emailStr];
}
else
return NO;
You probably should also trim whitespace as part of your email validation code as this check will fail if there is a trailing space for example.

Related

Password validation in UITextField in iOS 10 --> Objective C

I'm having 1 UITextfield for password in my iPhone application.
I want to validate this textfield with the following validation.
Must be at least 6 characters
Must contain at least one english letter, one digit and Remaining all
special characters are make as optional (ie not mandetory)
how can I restrict the UITextField with above requirements. please anyone help me out to do this..
Use this method to validate your password:
-(BOOL) isPasswordValid:(NSString *)password {
NSCharacterSet *upperCaseChars = [NSCharacterSet characterSetWithCharactersInString:#"ABCDEFGHIJKLKMNOPQRSTUVWXYZ"];
NSCharacterSet *lowerCaseChars = [NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyz"];
//NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
if ( [password length]<7 )
return NO; //too short
NSRange range;
range = [password rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
if ( !range.length )
return NO; // no letter
range = [password rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]];
if ( !range.length )
return NO; // no number;
range = [password rangeOfCharacterFromSet:upperCaseChars];
if ( !range.length )
return NO; // no uppercase letter;
range = [password rangeOfCharacterFromSet:lowerCaseChars];
if ( !range.length )
return NO; // no lowerCase Chars;
return YES;
}
Below is what I use using RegEx
NSString *passwordRegex = #"^.*(?=.{6,})(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$!&]).*$";
NSPredicate *passwordTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", passwordRegex];
if (![passwordTest evaluateWithObject:passwordTF.text]) {
// Password must be at least 6 character, containing lowercase letter, one uppercase letter, digits, and special character (!##$&)
}
Try this :
-(BOOL)isValidPasswordWithText:(UITextField *)textfield{
NSString *regex1 = #"^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d$#$!%*#?&]{6,}$";
NSPredicate *test1 = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", regex1];
return [test1 evaluateWithObject:textfield.text] ;
}
Inspired by Vamshi Krishna's answer, I think it could be more simple.
The decimalDigitCharacterSet can match any digital characters. Since the OP's intention didn't mention the upper case issue, so the letterCharacterSet should be enough here.
FYI:
BOOL ValidatePassword(NSString *candidate)
{
if (candidate.length < 6) {
return NO;
}
BOOL foundLetter = [candidate rangeOfCharacterFromSet:NSCharacterSet.letterCharacterSet].location != NSNotFound;
BOOL foundDigit = [candidate rangeOfCharacterFromSet:NSCharacterSet.decimalDigitCharacterSet].location != NSNotFound;
return foundLetter && foundDigit;
}

Check that string contains a character from set of characters

I need to check the complexity of a password. One of the conditions is that the password must contain at least one number. I've tried the following approach but it does not give me expected results and I don't know what's wrong.
NSString *regexpNumbers = #"[0-9]+";
NSPredicate *predicateNumbers = [NSPredicate predicateWithFormat:#"SELF CONTAINS %#", regexpNumbers];
result &= [predicateNumbers evaluateWithObject:password];
evaluateWithObject: method returns NO even if the password contains some number.
Using rangeOfCharacterFromSet:
You can create your own character set like the way:
NSCharacterSet *s = [NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_"];
s = [s invertedSet];
NSString *string = #"String to find";
NSRange r = [string rangeOfCharacterFromSet:s];
if (r.location != NSNotFound) {
NSLog(#"the string contains illegal characters");
} else {
NSLog(#"Found!!!");
}
Using NSPredicate:
NSString *myRegex = #"[A-Z0-9a-z_]*";
NSPredicate *myTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", myRegex];
NSString *string = #"String to find";
BOOL valid = [myTest evaluateWithObject:string];
When using NSPredicate with regex you need to use MATCHES, not CONTAINS (which is used for direct literal comparison).
Arguably you should't be doing this though. There is an argument that it should be done on the server.
Instead of using regex you could also look to use rangeOfCharacterFromSet: and NSCharacterSet for each of your checks.

check if one big string contains another string using NSPredicate or regular expression

NSString *string = #"A long term stackoverflow.html";
NSString *expression = #"stack(.*).html";
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", expression];
BOOL match = [predicate evaluateWithObject:string]
if(match){
NSLog(#"found");
} else {
NSLog(#"not found");
}
how can i search if expression is present in string or not. above code is working for one word. but not if i put some more words in string to be searched
If you would like to check a string with a regex value then you should use NSRegularExpression not NSPredicate.
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"stack(.*).html" options:0 error:nil];
Then you can use the functions to find matches...
NSString *string = #"stackoverflow.html";
NSUInteger matchCount = [regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, string.length)];
NSLog(#"Number of matches = %d", matchCount);
Note: I'm terrible at creating regex patterns so I have just used your pattern and example. I have no idea if the pattern will actually find a match in this string but if there is a match it will work.
NSPredicate only matches complete strings, so you should change your pattern to cover the whole string:
NSString *expression = #".*stack(.*).html.*";
However, your original pattern will also match something like "stack my files high as html", so you may want to read up on your regex patterns.
Improve your question , but see below answer for your question
NSString *string = #"This is the main stringsss which needs to be searched for some text the texts can be any big. let us see";
if ([string rangeOfString:#"."].location == NSNotFound) {
NSLog(#"string does not contains");
} else {
NSLog(#"string contains !");
}

Pull first name and last initial from string

I have an NSString that contains a users full name. Some names are in the standard first and last formation (Kyle Begeman) and others are just a single name (TechCrunch).
How would I grab the first name as is and then the first initial of the last name, and if there is only one name, just grab the whole name?
Basically I want the above to be turned into Kyle B. or just TechCrunch depending on the name.
NSString *username = #"Kyle Begeman"
NSString *otherUserName = #"TechCrunch"
converted to
#"Kyle B"
// No conversion because it is a single word name
#"TechCrunch"
Using substringToIndex is how I can grab the first letter in the whole string, and I know there is a way to separate the string by #" " whitespace into an array but I can figure out how to easily produce the result the way it needs to be.
Any help would be great!
(NSString*)firstNameWithInitial:(NSString*)userName {
NSArray *array = [userName componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
array = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF != ''"]];
NSString *firstName = [array objectAtIndex:0];
NSString finalNameString;
if ([array count] > 1) {
NSString *lastNameInitial = [[array objectAtIndex:1] substringToIndex:1];
finalNameString = [firstName stringByAppendingString:[NSString stringWithFormat:#" %#", lastNameInitial]];
else {
finalNameString = firstName;
}
return finalNameString;
}
This function should return what you need. Note that you can modify this to work with people who have more than 2 names, by checking the number of objects in the array.
Find a position pos of the first space in the string. If there is no space, or if the space is the last character of the string, then return the entire string; otherwise, return substring in the range from zero to pos+1, inclusive:
NSRange range = [str rangeOfString:#" "];
if (range.location == NSNotFound || range.location == str.length-1) {
return str;
} else {
return [str substringToIndex:range.location+1];
}
You could use NSScanner to find substrings.
NSString *name = #"Some name";
NSString *firstName;
NSString *lastName;
NSScanner *scanner = [NSScanner scannerWithString:name];
[scanner scanUpToString:#" " intoString:&firstName]; // Scan all characters up to the first space
[scanner scanUpToString:#"" intoString:&lastName]; // Scan remaining characters
if (lastName != nil) {
// It was no space and lastName is empty
} else {
// There was at least one space and lastName contains a string
}

NSPredicate for mobile number validation

How to validate a phone number (NSString *) by NSPredicate?
Rules:
minimum 10 digits
maximum 10 digits
the first digit must be 7,8 or 9
Thanks
An NSPredicate based on a regular expression will fit your requirements.
NSString *stringToBeTested = #"8123456789";
NSString *mobileNumberPattern = #"[789][0-9]{9}";
NSPredicate *mobileNumberPred = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", mobileNumberPattern];
BOOL matched = [mobileNumberPred evaluateWithObject:stringToBeTested];
You don't need to keep the pattern in a string by itself, but regexes are complicated enough already so it makes the overall code clearer if you keep it out of the NSPredicate format string.
You can just use below code
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; // return NO to not change text
{
if(textField.tag == 111)
{
if([self MobileNumberValidate:string] == TRUE)
return YES;
else
return NO;
}
return YES;
}
#pragma mark - Mobile Number validation
- (BOOL)MobileNumberValidate:(NSString*)number
{
NSString *numberRegEx = #"[0-9]";
NSPredicate *numberTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", numberRegEx];
if ([numberTest evaluateWithObject:number] == YES)
return TRUE;
else
return FALSE;
}
NSString *phoneNumber = #"1234567890";
NSString *phoneRegex = #"[789][0-9]{3}([0-9]{6})?";
NSPredicate *test = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", phoneRegex];
BOOL matches = [test evaluateWithObject:phoneNumber];
Below code will work for your requirement:
Function:
-(BOOL)validatePhone:(NSString *)enteredPhoneNumber
{
NSString *phoneRegex = #"[789][0-9]{9}";
// OR below for advanced type
//NSString *phoneRegex = #"^((\\+)|(00))[0-9]{6,14}$";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", phoneRegex];
return [phoneTest evaluateWithObject:enteredPhoneNumber];
}
Call it:
if ([self validatePhone:#"9833112299"])
{
NSLog(#"Valid Phone Number");
}
else
{
NSLog(#"Invalid Phone Number");
}
Make it Global using 'extension' use it wherever required
In any one of your view controller class at the end after last } paste below code
extension String
{
func validateMobile() -> Bool
{
return NSPredicate(format: "SELF MATCHES %#","[789][0-9].{9}").evaluate(with: self)
}
}
when you want to validate yourTxtField in any ViewController class simply call as below:
if (yourTxtField.text?.validateMobile())!
{
print("It is 10 digit, starting with 7/8/9")
}
else
{
print("Invalid mobile number")
}

Resources