I searched a lot over Google, but cant find a valid solution for best way to remove special characters'&' from Text Field in iPhone
I only want to remove or delimit user to enter '&' keyword.
I know that I have to do something in function
- (BOOL)textField:(UITextField *)textFieldBeingChanged shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
But what exactly not getting it properly.
Thanks in advance.....
See if this works :
-(NSString *) formatIdentificationNumber:(NSString *)string
{
NSCharacterSet * invalidNumberSet = [NSCharacterSet characterSetWithCharactersInString:#"\n_!##$%^&*()[]{}'\".,<>:;|\\/?+=\t~` "];
NSString * result = #"";
NSScanner * scanner = [NSScanner scannerWithString:string];
NSString * scannerResult;
[scanner setCharactersToBeSkipped:nil];
while (![scanner isAtEnd])
{
if([scanner scanUpToCharactersFromSet:invalidNumberSet intoString:&scannerResult])
{
result = [result stringByAppendingString:scannerResult];
}
else
{
if(![scanner isAtEnd])
{
[scanner setScanLocation:[scanner scanLocation]+1];
}
}
}
return result;
}
Related
This question already has answers here:
Limiting text field entry to only one decimal point
(10 answers)
Closed 9 years ago.
I have tried with this code as follow
this helps me to allow user to enter only numbers and dot (decimal point)
But the problem is user can allow n number of decimals in this method.
I want to allow only one decimal
and only two digits after the decima
like 123.00 , 123423432353.99
but not like 123.4.4 , 123.12345, 123...23
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (string.length == 0) {
return YES;
}
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789."];
for (int i = 0; i < [string length]; i++) {
unichar c = [string characterAtIndex:i];
if ([myCharSet characterIsMember:c]) {
return YES;
}
}
UIAlertView *av = [[UIAlertView alloc] initWithTitle:nil message:#"Invalid input" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[av show];
return NO;
}
How to allow user to enter only one decimal the text field that too allow only two digits after the decimal
thanks in advance
Best practices Use RegularExpressions whenever you have to perform any string format validation like Email,Phone Number,Currency etc.
This surely will solve your problem. Here sample code below:
First create instance of NSRegularExpression
NSError error;
NSRegularExpression * regExp = [[NSRegularExpression alloc]initWithPattern:#"^\\d{0,10}(([.]\\d{1,2})|([.]))?$" options:NSRegularExpressionCaseInsensitive error:&error];
then use in your relevant method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString * existingText = textField.text;
NSString * completeText = [existingText stringByAppendingFormat:#"%#",string];
if ([regExp numberOfMatchesInString:completeText options:0 range:NSMakeRange(0, [completeText length])])
{
if ([completeText isEqualToString:#"."])
[textField insertText:#"0"];
return YES;
}
else
return NO;
}
Use and let me know if it works.
Please try to use this one...It may helps you and please implement your functionality.This code for only 2 digit after "."
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSArray *sep = [newString componentsSeparatedByString:#"."];
if([sep count]>=2)
{
NSString *sepStr=[NSString stringWithFormat:#"%#",[sep objectAtIndex:1]];
return !([sepStr length]>2);
}
return YES;
In my app. I want to validate textfield with Special characters,
Ex.
if user press the ? from keypad than user not able to enter the ? in Textfield,
Please any one suggest, How can i do that?
Try like below it will help you.It will accept only letters
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
//For avoiding user to enter non digital number..
if([[string stringByTrimmingCharactersInSet:[[NSCharacterSet letterCharacterSet] invertedSet]] isEqualToString:#""])
{
return NO;
}
else
{
return YES;
}
}
check this
use
- (BOOL) textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)textEntered
See if this works :
-(NSString *) formatIdentificationNumber:(NSString *)string
{
NSCharacterSet * invalidNumberSet = [NSCharacterSet characterSetWithCharactersInString:#"\n_!##$%^&*()[]{}'\".,<>:;|\\/?+=\t~` "];
NSString * result = #"";
NSScanner * scanner = [NSScanner scannerWithString:string];
NSString * scannerResult;
[scanner setCharactersToBeSkipped:nil];
while (![scanner isAtEnd])
{
if([scanner scanUpToCharactersFromSet:invalidNumberSet intoString:&scannerResult])
{
result = [result stringByAppendingString:scannerResult];
}
else
{
if(![scanner isAtEnd])
{
[scanner setScanLocation:[scanner scanLocation]+1];
}
}
}
return result;
}
I have a UITextField where user can enter a name and save it. But, user should not be allowed to enter blank spaces in the textFiled.
1 - How can I find out,if user has entered two blank spaces or complete blank spaces in the textFiled
2 - How can i know if the textFiled is filled only with blank spaces
edit - It is invalid to enter only white spaces(blank spaces)
You can "trim" the text, that is remove all the whitespace at the start and end. If all that's left is an empty string, then only whitespace (or nothing) was entered.
NSString *rawString = [textField text];
NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *trimmed = [rawString stringByTrimmingCharactersInSet:whitespace];
if ([trimmed length] == 0) {
// Text was empty or only whitespace.
}
If you want to check whether there is any whitespace (anywhere in the text), you can do it like this:
NSRange range = [rawString rangeOfCharacterFromSet:whitespace];
if (range.location != NSNotFound) {
// There is whitespace.
}
If you want to prevent the user from entering whitespace at all, see #Hanon's solution.
if you really want to 'restrict' user from entering white space
you can implement the following method in UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string];
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
if ([resultingString rangeOfCharacterFromSet:whitespaceSet].location == NSNotFound) {
return YES;
} else {
return NO;
}
}
If user enter space in the field, there is no change in the current text
Use following lines of code
NSString *str_test = #"Example ";
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
if([str_test rangeOfCharacterFromSet:whitespaceSet].location!=NSNotFound)
{
NSLog(#"Found");
}
if you want to restrict user use below code
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([string isEqualToString:#" "])
{
return NO
}
else
{
return YES
}
}
UPD: Swift 2.0 Support
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let whitespaceSet = NSCharacterSet.whitespaceCharacterSet()
let range = string.rangeOfCharacterFromSet(whitespaceSet)
if let _ = range {
return false
}
else {
return true
}
}
I had a same condition not allowing user to input blank field
Here is my code and check statement
- (IBAction)acceptButtonClicked:(UIButton *)sender {
if ([self textFieldBlankorNot:fullNametext]) {
fullNametext.text=#"na";
}
// saving value to dictionary and sending to server
}
-(BOOL)textFieldBlankorNot:(UITextField *)textfield{
NSString *rawString = [textfield text];
NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *trimmed = [rawString stringByTrimmingCharactersInSet:whitespace];
if ([trimmed length] == 0)
return YES;
else
return NO;
}
Heres Swift 3 version
let whitespaceSet = NSCharacterSet.whitespaces
let range = string.rangeOfCharacter(from: whitespaceSet)
if let _ = range {
return false
}
else {
return true
}
In Swift,
if you want to restrict the user, you can use contains()
For Example,
if userTextField.text!.contains(" "){
//your code here.....
}
Here's what I did using stringByReplacingOccurrencesOfString.
- (BOOL)validateFields
{
NSString *temp = [textField.text stringByReplacingOccurrencesOfString:#" "
withString:#""
options:NSLiteralSearch
range:NSMakeRange(0, textField.text.length)];
if ([temp length] == 0) {
// Alert view with message #"Please enter something."
return NO;
}
}
#Hanon's answer is the pretty neat, but what I needed was to allow at least 1 white space, so based on Hanon's solution I made this one:
I declared a local variable called whitespaceCount to keep the counts of the white spaces.
Hope this helps anybody!
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
if ([string rangeOfCharacterFromSet:whitespaceSet].location != NSNotFound)
{
whitespaceCount++;
if (whitespaceCount > 1)
{
return NO;
}
}
else
{
whitespaceCount = 0;
return YES;
}
}
I want user to not use any extra spaces in the text field. How to do that?
Description : I have a text field which I am using for "Title of Something". I don't want to allow any user to give extra spaces/only spaces.
Regards
Here small snippet for UITextFieldDelegate:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if([[textField text] length] > 0) {
if([[textField text] characterAtIndex:([[textField text] length]-1)] == ' ' &&
[string isEqualToString:#" "]) return NO;
}
return YES;
}
You can trim the string when received:
NSString *string = #" spaces in front and at the end ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(trimmedString)
Also if you want to remove any double spaces inside the string i think this would do the trick:
NSString *noSpaces = [[string componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString: #" "];
just try this
NSString *t1= [txt.text stringByReplacingOccurrencesOfString:#" " withString:#""]
i want to validate a text field to accept only characters while typing in it.....
I use the following for integers but I guess you could easily modify it to scan for strings/chars (see NSScanner):
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string];
// This allows backspace
if ([resultingString length] == 0) {
return true;
}
NSUInteger holder;
NSScanner *scan = [NSScanner scannerWithString: resultingString];
return [scan scanInteger: &holder] && [scan isAtEnd];
}
Don't forget to set the UITextField delegate appropriately :)