0

I am using a textfield with phone number. The copy paste is enable in Textfield. The textfield should not take non numeric value.

But the problem is that if paste any String i takes non numeric value.

I have tried below code but not getting success:

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{

    if (action == @selector(paste:))
    {
        UIPasteboard *pasteboard =[UIPasteboard generalPasteboard];
        NSLog(@"%@",pasteboard.string);
        if ([self isAllDigits:pasteboard.string]) {
        return YES;
        }
        return NO;

    }
    return [super canPerformAction:action withSender:sender];
}
guru
  • 2,727
  • 3
  • 27
  • 39

3 Answers3

0

Something like this:

- (BOOL)numeric:(NSString *)aString {
    NSScanner *scanner = [NSScanner scannerWithString: aString];
    if ([scanner scanFloat:NULL]) {
        return [scanner isAtEnd];
    }
    return NO;
}
whoover
  • 89
  • 1
  • 7
0

Here's the example to do it with custom class of UITextfield But in Swift ;), Just create a new swift file and paste it. Change your text filed class name as "MyTextfield" ( change class name whatever you want ). PFA to see the storyboard view at property window.

enter image description here

import UIKit

@IBDesignable

class MyTextField: UITextField {

@IBInspectable var isPasteEnabled: Bool = true

@IBInspectable var isCopyEnabled: Bool = true

override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
    switch action {
    case #selector(UIResponderStandardEditActions.paste(_:)) where !isPasteEnabled,
         #selector(UIResponderStandardEditActions.copy(_:)) where !isCopyEnabled:
        return false
    default:
        return super.canPerformAction(action, withSender: sender)
    }
  }
}
0

Finally solved by putting below code in UITextfield subclass.

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if ((self.keyboardType = UIKeyboardTypePhonePad))
    {
        if (action == @selector(paste:))
        {
            UIPasteboard *pasteboard =[UIPasteboard generalPasteboard];
            NSLog(@"%@",pasteboard.string);
            if ([self isAllDigits:pasteboard.string]) {
                return YES;
            }
            return NO;

        }
    }
    return [super canPerformAction:action withSender:sender];
    //prevent uitextfield to paste non numeric string
}
- (BOOL) isAllDigits:(NSString *)testString
{
    NSCharacterSet* nonNumbers = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    NSRange r = [testString rangeOfCharacterFromSet: nonNumbers];
    return r.location == NSNotFound;
}
guru
  • 2,727
  • 3
  • 27
  • 39