Validate textfield with special character - iphone

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

Related

Decimal style improvement objective c calculator

I'm doing the calculator tutorial for iOS and I've done some research for doing the decimal style. So far on my research, I've gone through this code below
- (IBAction)digitPressed:(UIButton *)sender {
NSString *digit = sender.currentTitle;
NSString *decimal = #".";
BOOL decimalAlreadyEntered = [self.display.text rangeOfString:decimal].location == NSNotFound ? NO : YES;
if (self.userIsInTheMiddleOfEnteringANumber) {
if (([digit isEqual:decimal] && !decimalAlreadyEntered) || !([digit isEqual:decimal])) {
[self.display setText:[[self.display text] stringByAppendingString:digit]];
}
}
else if ([self.display.text isEqual:#"0"] && digit == decimal){
[self.display setText:[[self.display text] stringByAppendingString:digit]];
self.userIsInTheMiddleOfEnteringANumber = YES;
}
else {
[self.display setText:digit];
self.userIsInTheMiddleOfEnteringANumber = YES;
}
}
This code helped me to prevent multiple decimal points being pressed by the user, and limit it only to one (as in 2.09). Cool! However during the start of the app, when I press on the decimal point and pressed on a number, say 1, the label will only display ( .1) instead of (0.1) . Any help for the improvement is much appreciated :)
In - (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string you can check whether first value is "." then replace text value by "0.", whatever user has entered.And perform this check only when textfield value is ".something".
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *symbol = [[NSLocale currentLocale] objectForKey:NSLocaleDecimalSeparator];
if (range.location == 0 && [string isEqualToString:symbol]) {
// decimalseparator is first
textField.text = [NSString stringWithFormat:#"0%#",textField.text];
return YES;
}
}

How to know if a UITextField in iOS has blank spaces

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

How to remove special characters'&' from UItextField iPhone

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

how to validate a Text field to accept only Characters at run Time in iphone

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 :)

Iphone UITextField only integer

I have a UITextField in my IB and I want to check out if the user entered only numbers (no char)and get the integer value.
I get the integer value of the UITextField like that :
int integer = [myUITexrtField.text intValue];
When I put a character ( , ; . ) it return me 0 and I don't know how to detect that it is not only numbers.
How can I do?
Implementing shouldChangeCharactersInRange method as below does not allow the user input non-numeric characters.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0) || [string isEqualToString:#""];
}
This returns YES if the string is numeric, NO otherwise. the [string isEqualToString#""] is to support the backspace key to delete.
I love this approach because it's clean.
Be sure to set your text field delegate
Use the following function to ensure user can type in numbers only:
- (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;
}
}
Try this: It will stop user to enter any character other then numbers
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([string rangeOfCharacterFromSet:nonNumberSet].location != NSNotFound)
{
return NO;
}
return YES;
}
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Objective-C
Or you could ensure that only the numeric keyboard appears when the focus comes on the field
To only allow for numeric input:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
return [string isEqualToString:#""] ||
([string stringByTrimmingCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].length > 0);
}
To test for an integer:
- (BOOL)isNumeric:(NSString *)input {
for (int i = 0; i < [input length]; i++) {
char c = [input characterAtIndex:i];
// Allow a leading '-' for negative integers
if (!((c == '-' && i == 0) || (c >= '0' && c <= '9'))) {
return NO;
}
}
return YES;
}
Answer by #devsan is incorrect. If a user pastes anything with a a number such as "1abc" her code would break
It should be (allow replacement only if all the chars are digits):
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
return ([string stringByTrimmingCharactersInSet:nonNumberSet].length == string.length) || [string isEqualToString:#""];
}
You could also use UITextFieldDelegate method
textField:shouldChangeCharactersInRange:replacementString:
to live check that each time the user press a key, it is a simple digit, so that he/she knows that only int value is to be entered in the field.
Want to allow negative numbers as well?
Elaborating on davsan's answer, here is a solution that supports entering negative as well as positive numbers, and disallows anything else.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0) || [string isEqualToString:#""] || ([textField.text isEqualToString:#""] && [string isEqualToString:#"-"]);
return YES;
}
This code is work with localisation too .
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([string isEqualToString:#""]) return YES;
NSCharacterSet *characterSet = nil;
characterSet = [NSCharacterSet decimalDigitCharacterSet];
NSRange location = [string rangeOfCharacterFromSet:characterSet];
return (location.location != NSNotFound);
if(characterSet == nil) return YES;
return YES;
}