InUITextBoxfield,i insert some value,and I Want to use RegularExpressions match the string ..now i want the text box text should be match for only numeric digits upto 3 when I press button then it should work...
What I am trying is which is not working::-
-(IBAction)ButtonPress{
NSString *string =activity.text;
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"^[0-9]{1,3}$" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#""];
if ([activity.text isEqualToString:modifiedString ])
{ // work only if this matches numeric value from the text box text
}}
- (BOOL)NumberValidation:(NSString *)string {
NSUInteger newLength = [string length];
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:#"1234567890"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
return (([string isEqualToString:filtered])&&(newLength <= 3));
}
in your button action event just use this like bellow...
-(IBAction)ButtonPress{
if ([self NumberValidation:activity.text]) {
NSLog(#"Macth here");
}
else {
NSLog(#"Not Match here");
}
}
Your code replaces all matches with an empty string, so if there is a match, it will be replaced by an empty string and your check will never work. Instead, just ask the regular expression for the range of the first match:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"^[0-9]{1,3}$" options:NSRegularExpressionCaseInsensitive error:NULL];
NSRange range = [regex rangeOfFirstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
if(range.location != NSNotFound)
{
// The regex matches the whole string, so if a match is found, the string is valid
// Also, your code here
}
You can also just ask for the number of matches, if it's not zero, the string contains a number between 0 and 999 because your regex matches for the whole string.
Please try following code.
- (BOOL) validate: (NSString *) candidate {
NSString *digitRegex = #"^[0-9]{1,3}$";
NSPredicate *regTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", digitRegex];
return [regTest evaluateWithObject:candidate];
}
-(IBAction)btnTapped:(id)sender{
if([self validate:[txtEmail text]] ==1)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message" message:#"You Enter Correct id." delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
[alert release];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message" message:#"You Enter Incoorect id." delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
[alert release];
}
}
Related
I have to put validation on a UITextField for user input.
The user must input into the textfield a value
i.e. 70-80 or 85 mean num-num or num
Right now, I just allow to user to input only digits& - but drawback is that user can also input - number of times.
// My code is as follow
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789-"] invertedSet];
if (([txtMarks.text rangeOfCharacterFromSet:set].location != NSNotFound )||[txtMarks.text isEqualToString:#""] ) {
UIAlertView *alt=[[UIAlertView alloc]initWithTitle:#"Error" message:#"Invalid Input" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alt show];
[alt release];
}
Simply Try this,
int times = [[txtMarks.text componentsSeparatedByString:#"-"] count]-1;
if(times>1)
{
UIAlertView *alt=[[UIAlertView alloc]initWithTitle:#"Error" message:#"'-' used more than one" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alt show];
[alt release];
}
EDIT 1
Using NSPredicate we can do it. Try this,
NSString *regex = #"[0-9]+(-[0-9]+)?";
NSPredicate *testRegex = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", regex];
if([testRegex evaluateWithObject:textField.text])
NSLog(#"Match");
else
NSLog(#"Do not match");
Hope that can help.
Try this first find whether your string contains -
Here subtring is -
if ([txtMarks.text hasPrefix:#"-"]||[txtMarks.text hasSuffix:#"-"])
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"sorry " message:#"invalid inoput as it has - at start or end" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
else
{
NSRange textRange;
textRange =[string rangeOfString:substring];
if(textRange.location == NSNotFound)
{
//Does not contain the substring
NSlog(#" string contains only num")
}
else
{
int times = [[txtMarks.text componentsSeparatedByString:#"-"] count];
if(times==2)
{
Nslog(#"num-num input")
}
else
{
UIAlertView *alt=[[UIAlertView alloc]initWithTitle:#"Error" message:#"'-' used more than one" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alt show];
[alt release];
}
}
}
Try it using the following regular expression, It restricts user to enter more than one -.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSString *expression = #"^([0-9]{1,}+)?(\\-([0-9]{1,})?)?$";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression
options:NSRegularExpressionCaseInsensitive
error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
options:0
range:NSMakeRange(0, [newString length])];
if (numberOfMatches == 0)
{
return NO;
}
return YES;
}
i have a text field in Contact screen and the user need to enter email address to send me message.
Whats the best way to ensure the user has entered a valid email address such as:
a#b.com / net / org / co.il
abc#gmail.com
abc#yahoo.com
etc..
Thanks
Try the following:
- (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];
}
-(IBAction)btnTapped:(id)sender{
if([self validateEmail:[txtEmail text]] ==1)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message" message:#"You Enter Correct Email id." delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
[alert release];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message" message:#"You Enter Incoorect Email id." delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
[alert release];
}
}
Use this textField delegate function as this will be called on every text entered:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *strEnteredText = textField.text;
if(strEnteredText.length>0)
{
if([self validateEmail:strEnteredText])
{
//Valid email
//Use UILabel to give message
// BOOL email = true to know email is valid when submit button tapped
}
else
{
//Not Valid email
//Use UILabel to give message
// BOOl emaiL = false to know email is valid when submit button tapped
}
}
}
Add this method .h file
- (BOOL) validateEmail: (NSString *) enteredText
{
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:enteredText];
}
Swift
extension String {
func isValidEmail() -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,10}"
let emailTest = NSPredicate(format:"SELF MATCHES %#", emailRegEx)
let result = emailTest.evaluateWithObject(self)
return result
}
}
"jim#off.com".isValidEmail() //true
"jim.com".isValidEmail() // false
I have a calculator app in which I have a textfield in which if I enter any number; then it works fine. If I do not enter a number then it shows alert. I also want the user to be able to enter 1.5 but when I do this it shows alert "enter a number please"
So how can I enter decimal number? I am using the following code :
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789"] invertedSet];
NSString*string=costToClientTextField.text;
if ([string rangeOfCharacterFromSet:set].location != NSNotFound) {
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Warning" message:#"Only a number can be entered into this input field " delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
costToClientTextField.text=#"";
}
Add the "." in your set, like so
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789."] invertedSet];
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber* candidateNumber;
NSString* candidateString = [textField.text stringByReplacingCharactersInRange:range withString:string];
range = NSMakeRange(0, [candidateString length]);
[numberFormatter getObjectValue:&candidateNumber forString:candidateString range:&range error:nil];
if (([candidateString length] > 0) && (candidateNumber == nil || range.length < [candidateString length])) {
return NO;
}
else
{
return YES;
}
}
Maybe this will help you. also put keyboard type number and punctuation.
I have a login form where the user can login only with the valid memberID and password. If the user enter correct enamel and password i get a result string contains the user information that the user created in the signup process, if it the password is wrong it shows the status 400 as the result string, the result string is the json array which contains one f the above values, one thing is the if the success login occur it gives the staus 200 along with the user information, my need is to retrieve the status message from the array and i need to validate it within the app, if the login success(status 200) it needs to be redirected to the main page; if it is(status 400) it shows a unsuccessful login message.
my code:
EDit
-(IBAction)_clicksbtnsignIN:(id) sender
{
[_txtmemberId resignFirstResponder];
[_txtpassword resignFirstResponder];
NSString *connectionstring = [[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:#"http://www.google.com"]];
if ([connectionstring length]==0) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"you are not connected to the internet" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *emailString = _txtmemberId.text; // storing the entered email in a string.
// Regular expression to checl the email format.
NSString *emailReg = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailReg];
//[pool drain];
if (_txtmemberId.text.length == 0 || _txtpassword.text.length == 0) {
UIAlertView *alertblnk = [[UIAlertView alloc]initWithTitle:#"ALERT" message:#"Fill the required text fields" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alertblnk show];
[alertblnk release];
}
if (([emailTest evaluateWithObject:emailString] != YES) || [emailString isEqualToString:#""])
{
UIAlertView *loginalert = [[UIAlertView alloc] initWithTitle:#" Alert" message:#"Invalid Email ID" delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[loginalert show];
[loginalert release];
}
else {
[_spinner startAnimating];
NSString *uname = _txtmemberId.text;
NSString *pwd = _txtpassword.text;
NSString *urlVal = #"http://dev.eltouchapps.net/api/?app=1&type=m1&action=t2&var1=";
NSString *urlVal1 = [urlVal stringByAppendingString:uname];
NSString *urlVal2 = [urlVal1 stringByAppendingString:#"&var2="];
NSString *urlVal3 = [urlVal2 stringByAppendingString:pwd];
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)urlVal3,NULL, (CFStringRef)#"\n" "",kCFStringEncodingUTF8 );
NSURL *url = [NSURL URLWithString:encodedString];
NSString *resultString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
UIAlertView *loginalert = [[UIAlertView alloc] initWithTitle:#" Message" message:resultString delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[loginalert show];
[loginalert release];
lblresult.text = resultString;
NSString *responseString = [resultString responseString];
NSLog(#"Got Profile: %#", responseString);
NSMutableDictionary *responseJSON = [responseString JSONValue];
NSString *firstName;
if ([[responseJSON valueForKey:#"Status"] isEqualToString:#"200"]) // if success
{
ParallelReadViewController *detailViewController = [[ParallelReadViewController alloc] initWithNibName:#"ParallelReadViewController" bundle:nil];
//detailViewController.firstString = firstString;
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
// do something
firstName = [responseJSON valueForKey:#"FirstName"];
}
}
}
}
Result string is why i get from the server. I know there is parsing of JSONB array we want , but i didn't know how to done this.
Thanks in advance.
based on assumption of your response , try below code
NSString *resultString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSMutableDictionary *responseJSON = (NSMutableDictionary *)[responseString JSONValue];
NSString *firstName;
if ([[responseJSON valueForKey:#"Status"] isEqualToString:#"200"]) // if success
{
// do something
firstName = [responseJSON valueForKey:#"FirstName"];
}
Hope it gives you an idea.
Check out this JSON framework: https://github.com/stig/json-framework/
I created UITextField. I need only 4 numeric characters only allowed that textfield.
I used the following code and get result.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber* candidateNumber;
NSString* candidateString = [textField.text stringByReplacingCharactersInRange:range withString:string];
range = NSMakeRange(0, [candidateString length]);
[numberFormatter getObjectValue:&candidateNumber forString:candidateString range:&range error:nil];
NSUInteger newLength = [passwordfield.text length];
if(newLength>=4)
{
[passwordfield setText:[passwordfield.text substringToIndex:3]];
UIAlertView *alert = [[UIAlertView alloc] init];
[alert setTitle:#"Alert"];
[alert setMessage:#"Four Characters only allowed.."];
[alert setDelegate:self];
[alert addButtonWithTitle:#"Ok"];
[alert show];
}
if (([candidateString length] > 0) && (candidateNumber == nil || range.length < [candidateString length]))
{
return NO;
}
else
{
return YES;
}
}
But my problem is when I press delete key, last two characters are deleting
and same time alertview also display.
How to solve this issue?
You're making this more complex than it needs to be. When a user taps the backspace key, the incoming string is a blank string; [NSString string]. Here's a working solution:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
if (![numberFormatter numberFromString:string] && ![string isEqualToString:[NSString string]]) {
return NO;
}
if (textField.text.length + string.length > 4) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert"
message:#"Four Characters only allowed..."
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
[alert release];
return NO;
} else {
return YES;
}
}