NSPredicate for mobile number validation - ios

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")
}

Related

How to make a regular Expression for name Validation

I want to make a regular expression in which user can only enter alphabets.
I am using this piece of code to validate the UITextField.
I am validating the code in shouldChangeCharactersInRange method.
NSString *regex = #"[a-zA-Z]";
NSPredicate *testRegex = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", regex];
if(![testRegex evaluateWithObject:string])
return NO;
It is working fine but I can not delete using BacKspace button As my RegEx doesn't allow this.
How can I make a regular expression which supports alphabets and allow deletion.
Try this out:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)iRange replacementString:(NSString *)iText {
NSString *newString = [iTextView.text stringByReplacingCharactersInRange:iRange withString:iText];
NSString *abnRegex = #"[A-Za-z]+";
NSPredicate *abnTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", abnRegex];
return ([abnTest evaluateWithObject:newString] || newString.length == 0);
}
Can you try with this (Just a work around) :
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (range.length > 0)
{
// We're deleting
return YES;
}
else
{
// We're adding
NSString *regex = #"[a-zA-Z]";
NSPredicate *testRegex = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", regex];
if(![testRegex evaluateWithObject:string])
return NO;
else
return YES;
}

RegEx validation of techmahindra account

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.

Validating strings against given regex pattern?

I wrote simple method for checking if given array has at least one string, that matches provided pattern... but something is missing and not sure how to limit positive results only to full words, not just first substring that fits pattern.
+ (BOOL)hasWordsWithPattern:(NSString *)pattern inWords:(NSArray *)words{
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
for (NSString *s in words) {
if ([expression matchesInString:s
options:0
range:NSMakeRange(0, s.length)]) {
NSLog(#"there is a match!");
return YES;
}
}
NSLog(#"sorry, no match found!");
return NO;
}
Silly me, there is easier way to do that :) based on https://stackoverflow.com/a/5777016/1015049
+ (BOOL)hasWordsWithPattern:(NSString *)pattern inWords:(NSArray *)words{
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", pattern];
for (NSString *s in words) {
if ([predicate evaluateWithObject:s]) {
NSLog(#"there is a match!");
return YES;
}
}
NSLog(#"sorry, no match found!");
return NO;
}

UITextField to hold upto 10 numbers before decimal place and upto three numbers after decimal

I am looking for a code that allows me to hold upto 10 numbers before decimal place and upto three numbers after decimal.
Valid examples are:
1234567899.123 - maximum 10 numbers before decimal and 3 after decimal position.
123.123 - less than 10 numbers before decimal okay.
123456.1 - less than 3 numbers after decimal okay.
123 - Okay
I am using this function below:
-(BOOL)textField: (UITextField*)tectField shouldChangeCharactersInRange: (NSRange)range replacementString:(NSString*) string {
NSString *newStrn = [textField.text stringReplacingCharactersInRange: range withString: string];
NSArray *arrayofStrn = [newStrn componentsSeparatedByString:#"."]; //to keep only one decimal
if([arrayofStrn count]> 2) {
return NO;
}
else {
return YES;
}
}
Do not know how to proceed further to keep max limit of 10 numbers (less than 10 okay) before decimal and maximum limit of 3 numbers after decimal (less than 3 numbers or no numbers after decimal okay).
Thanks very much guys!
You could achieve this with a simple regex like this
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
NSString *editedString = [textField.text stringReplacingCharactersInRange:range withString:string];
NSString *regex = #"\\d{0,10}(\\.\\d{0,3})?"
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", regex];
return [predicate evaluateWithObject:editedString];
}
I've tested the above with the following inputs
#"1234567891", //=> YES
#"12345678912", //=> NO
#"1234567891.122", //=> YES
#"1234567891.1234", //=> NO
#".123", //=> YES
Inside your else statement put the following:
if([arrayofStrn count] < 2) {
if ([[arrayofStrn objectAtIndex:0] length] > 10) {
//Bad
} else {
//Good
}
} else {
if ([[arrayofStrn objectAtIndex:0] length] > 10 || [[arrayofStrn objectAtIndex:1] length] > 3) {
//Bad
} else {
//Good
}
}
Just as a note, you can retrieve the length of NSString like so:
theString.length or [theString length]
Here's Xcode 10 and Swift 4.2
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == txt_Amount{
let amountString: NSString = textField.text! as NSString
let newString: NSString = amountString.replacingCharacters(in: range, with: string) as NSString
let regex = "\\d{0,6}(\\.\\d{0,2})?"
let predicate = NSPredicate(format: "SELF MATCHES %#", regex)
return predicate.evaluate(with:newString)
}
return true
}

Email validation on textField in iOS

In iOS App, how to add Email validation on UITextField?
Use NSPredicate and Regex:
- (BOOL)validateEmailWithString:(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];
}
For a bunch of emails separated by a comma:
- (NSMutableArray*)validateEmailWithString:(NSString*)emails
{
NSMutableArray *validEmails = [[NSMutableArray alloc] init];
NSArray *emailArray = [emails componentsSeparatedByString:#","];
for (NSString *email in emailArray)
{
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:email])
[validEmails addObject:email];
}
return [validEmails autorelease];
}
Edited Answer: (It also validates extra dots )
- (BOOL)validateEmailWithString:(NSString*)checkString
{
BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
NSString *stricterFilterString = #"[A-Z0-9a-z\\._%+-]+#([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}";
NSString *laxString = #".+#([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*";
NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
return [emailTest evaluateWithObject:checkString];
}
Try this out
This checks exactly with top level domain names along with validation.
- (BOOL)validateEmail:(NSString *)inputText {
NSString *emailRegex = #"[A-Z0-9a-z][A-Z0-9a-z._%+-]*#[A-Za-z0-9][A-Za-z0-9.-]*\\.[A-Za-z]{2,6}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
NSRange aRange;
if([emailTest evaluateWithObject:inputText]) {
aRange = [inputText rangeOfString:#"." options:NSBackwardsSearch range:NSMakeRange(0, [inputText length])];
int indexOfDot = aRange.location;
//NSLog(#"aRange.location:%d - %d",aRange.location, indexOfDot);
if(aRange.location != NSNotFound) {
NSString *topLevelDomain = [inputText substringFromIndex:indexOfDot];
topLevelDomain = [topLevelDomain lowercaseString];
//NSLog(#"topleveldomains:%#",topLevelDomain);
NSSet *TLD;
TLD = [NSSet setWithObjects:#".aero", #".asia", #".biz", #".cat", #".com", #".coop", #".edu", #".gov", #".info", #".int", #".jobs", #".mil", #".mobi", #".museum", #".name", #".net", #".org", #".pro", #".tel", #".travel", #".ac", #".ad", #".ae", #".af", #".ag", #".ai", #".al", #".am", #".an", #".ao", #".aq", #".ar", #".as", #".at", #".au", #".aw", #".ax", #".az", #".ba", #".bb", #".bd", #".be", #".bf", #".bg", #".bh", #".bi", #".bj", #".bm", #".bn", #".bo", #".br", #".bs", #".bt", #".bv", #".bw", #".by", #".bz", #".ca", #".cc", #".cd", #".cf", #".cg", #".ch", #".ci", #".ck", #".cl", #".cm", #".cn", #".co", #".cr", #".cu", #".cv", #".cx", #".cy", #".cz", #".de", #".dj", #".dk", #".dm", #".do", #".dz", #".ec", #".ee", #".eg", #".er", #".es", #".et", #".eu", #".fi", #".fj", #".fk", #".fm", #".fo", #".fr", #".ga", #".gb", #".gd", #".ge", #".gf", #".gg", #".gh", #".gi", #".gl", #".gm", #".gn", #".gp", #".gq", #".gr", #".gs", #".gt", #".gu", #".gw", #".gy", #".hk", #".hm", #".hn", #".hr", #".ht", #".hu", #".id", #".ie", #" No", #".il", #".im", #".in", #".io", #".iq", #".ir", #".is", #".it", #".je", #".jm", #".jo", #".jp", #".ke", #".kg", #".kh", #".ki", #".km", #".kn", #".kp", #".kr", #".kw", #".ky", #".kz", #".la", #".lb", #".lc", #".li", #".lk", #".lr", #".ls", #".lt", #".lu", #".lv", #".ly", #".ma", #".mc", #".md", #".me", #".mg", #".mh", #".mk", #".ml", #".mm", #".mn", #".mo", #".mp", #".mq", #".mr", #".ms", #".mt", #".mu", #".mv", #".mw", #".mx", #".my", #".mz", #".na", #".nc", #".ne", #".nf", #".ng", #".ni", #".nl", #".no", #".np", #".nr", #".nu", #".nz", #".om", #".pa", #".pe", #".pf", #".pg", #".ph", #".pk", #".pl", #".pm", #".pn", #".pr", #".ps", #".pt", #".pw", #".py", #".qa", #".re", #".ro", #".rs", #".ru", #".rw", #".sa", #".sb", #".sc", #".sd", #".se", #".sg", #".sh", #".si", #".sj", #".sk", #".sl", #".sm", #".sn", #".so", #".sr", #".st", #".su", #".sv", #".sy", #".sz", #".tc", #".td", #".tf", #".tg", #".th", #".tj", #".tk", #".tl", #".tm", #".tn", #".to", #".tp", #".tr", #".tt", #".tv", #".tw", #".tz", #".ua", #".ug", #".uk", #".us", #".uy", #".uz", #".va", #".vc", #".ve", #".vg", #".vi", #".vn", #".vu", #".wf", #".ws", #".ye", #".yt", #".za", #".zm", #".zw", nil];
if(topLevelDomain != nil && ([TLD containsObject:topLevelDomain])) {
//NSLog(#"TLD contains topLevelDomain:%#",topLevelDomain);
return TRUE;
}
/*else {
NSLog(#"TLD DOEST NOT contains topLevelDomain:%#",topLevelDomain);
}*/
}
}
return FALSE;
}
Use the below code:-
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:userMailTextField.text] == YES)
{
//Do Something
}
else
{
NSLog(#"email not in proper format");
}
userMailTextField is the name of my textField (use your own).
I hope this code will help you!!!
Use Below code for "Swift language" For Email Validation
func ValidateEmailString (strEmail:NSString) -> Bool
{
let emailRegex = "[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let emailText = NSPredicate(format:"SELF MATCHES [c]%#",emailRegex)
return (emailText.evaluate(with: strEmail))
}
Thanks :)
NSRegularExpression is the Best Way to Validate Email Addresses with iOS 4.x and Later.
-(BOOL) validateEmail:(NSString*) emailString
{
NSString *regExPattern = #"^[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,4}$";
NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
NSUInteger regExMatches = [regEx numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])];
NSLog(#"%i", regExMatches);
if (regExMatches == 0) {
return NO;
}
else
return YES;
}
Usage :
if([self validateEmail:#"something#domain.com"]) {
//Email Address is valid.
}
else {
//Email Address is invalid.
}
- (BOOL)validateEmailAddress:(NSString*)yourEmail
{
//create a regex string which includes all email validation
NSString *emailRegex = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
//create predicate with format matching your regex string
NSPredicate *email = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
//return True if your email address matches the predicate just formed
return [email evaluateWithObject:yourEmail];`
}
--it's easy to validate your email id by calling validateEmail method:
-(BOOL)validateEmail:(NSString *)email
{
NSString *emailRegex = #"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
return [emailTest evaluateWithObject:email];
}
Verify your email id here....
BOOL eb=[self validateEmail:**youremailtextfield**];
if(!eb)
{
UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"Please enter correct email id"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertsuccess show];
[alertsuccess release];
}
Here the simple way to validate email in obj c
if(![self validEmail:self.emailTxtFld.text]) {
// here show alert not a valid email id
}
here valid email id method is
- (BOOL) validEmail:(NSString*) emailString {
if([emailString length]==0){
return NO;
}
NSString *regExPattern = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
NSUInteger regExMatches = [regEx numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])];
if (regExMatches == 0) {
return NO;
} else {
return YES;
}
}
In Swift 3.0 Version
if !validEmailId(inputText: userNameTxtFld.text!) {
print("Not Valid Emaild")
}
else {
print("valid email id")
}
func validEmailId(inputText: String)-> Bool {
print("validate emilId: \(inputText)")
let emailRegEx = "^(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?(?:(?:(?:[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+(?:\\.[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+)*)|(?:\"(?:(?:(?:(?: )*(?:(?:[!#-Z^-~]|\\[|\\])|(?:\\\\(?:\\t|[ -~]))))+(?: )*)|(?: )+)\"))(?:#)(?:(?:(?:[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)(?:\\.[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)*)|(?:\\[(?:(?:(?:(?:(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))\\.){3}(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))))|(?:(?:(?: )*[!-Z^-~])*(?: )*)|(?:[Vv][0-9A-Fa-f]+\\.[-A-Za-z0-9._~!$&'()*+,;=:]+))\\])))(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?$"
let emailTest = NSPredicate(format:"SELF MATCHES %#", emailRegEx)
let result = emailTest.evaluate(with: inputText)
return result
}
This works exactly
-(BOOL) emailValidation:(NSString *)emailTxt
{
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:emailTxt];
}
perfect validation for email. try this.
- (BOOL)validateEmailWithString:(NSString*)checkString
{
NSString *laxString = #".+#([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", laxString];
return [emailTest evaluateWithObject:checkString];
}
I'm author of DCKit library, which has DCMandatoryEmailTextField. This class does email validation automatically and highlights/unhighlights the text field when the user is typing a value:
Check it out: https://github.com/andrew8712/DCKit
Swift
func validateEmail(email:String) -> Bool {
let stricterFilter = false
let stricterFilterString = "[A-Z0-9a-z\\._%+-]+#([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}"
let laxString = ".+#([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*";
let emailRegex = stricterFilter ? stricterFilterString : laxString
let emailTest = NSPredicate(format: "SELF MATCHES %#", emailRegex)
return emailTest.evaluate(with: email);
}
Function:
- (BOOL)validateEmail:(NSString *)enteredEmailID
{
//checking valid email id or not
NSString *emailReg = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailReg];
return [emailTest evaluateWithObject:enteredEmailID];
}
Call it like:
if ([self validateEmail: textField.text])
{
//NSLog(#"Valid Email");
}
else
{
//NSLog(#"Invalid Email");
}
EDIT:
You can do this into textfield did end editing delegates or textfield should character change delegates
A version using NSRegularExpression and regex pattern copied from OWASP_Validation_Regex_Repository
+ (BOOL) isValidEmail:(NSString *)emailString {
NSError *error = NULL;
/**
* #see OWASP_Validation_Regex_Repository
*/
NSString *emailPattern = #"^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*#(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:emailPattern
options:NSRegularExpressionCaseInsensitive
error:&error];
NSUInteger matchCount = [regex numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])];
return matchCount > 0;
}

Resources