Allow only alpha numeric characters in UITextView

2019-07-10 07:21发布

问题:

Is there anyway i can allow user to enter only alpha numeric characters in a text view and no other character.

EDIT:

Tried,

if ([_txtView.text rangeOfCharacterFromSet:alphaSet].location != NSNotFound)
    {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Hello" message:@"Only alpha numeric characters are allowed" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        return;

    }

but this only works for some of the times

Thanks!!

回答1:

You can achieve that using [[[NSCharacterSet alphanumericCharacterSet] invertedSet]. This method will return a character set containing only characters that don’t exist in the receiver.

NSCharacterSet *charactersToBlock = [[NSCharacterSet alphanumericCharacterSet] invertedSet];

//Conform UITextField delegate and implement this method.

 - (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
 {
    return ([characters rangeOfCharacterFromSet:charactersToBlock].location == NSNotFound);
 }


回答2:

Try this:

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
            if (textField == txtWebsite) {
                    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 "];

                    if ([string rangeOfCharacterFromSet:set].location != NSNotFound) {
                        return YES;
                    }
                    else {
                        return NO;
                    }
            }
            else {
                    return YES;
            }
    }

write code in delegate method of uitextfield.



回答3:

set delegate for textview and override/implement test should change in range method

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text 
{
     NSCharacterSet *alphaSet = [NSCharacterSet alphanumericCharacterSet];
     BOOL valid = [[text stringByTrimmingCharactersInSet:alphaSet] isEqualToString:@""];
     return valid;    
}


回答4:


// Add this in ViewDidLoad or any init method NSCharacterSet *blockedCharacters = [[[NSCharacterSet alphanumericCharacterSet] invertedSet] retain];

then Set your textfield's delegate in nib file .

- (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
{
    return ([characters rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound);
}

Or there is another way in shouldChangeCharactersInRange method. You can check

{
    NSString *stringPlace = @"[a-z  A-Z]*";

    NSPredicate *testPlace = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stringPlace]; 
        BOOL matches = [testPlace evaluateWithObject:string];

        if (!matches && string.length > 5)
        {
            return NO;
        }
    return YES;
}


回答5:

Equivalent Swift 3 version of the answer provided by @user1113101

Though it's late to answer and there are other simple and great approaches, but this answer might be useful to someone.

This is simple and worked like a charm for me.

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    /// 1. replacementText is NOT empty means we are entering text or pasting text: perform the logic
    /// 2. replacementText is empty means we are deleting text: return true
    if text.characters.count > 0 {
        var allowedCharacters = CharacterSet.alphanumerics

        let unwantedStr = text.trimmingCharacters(in: allowedCharacters)
        return unwantedStr.characters.count == 0
    }

    return true
}

Note: This will work for pasting strings into the text field as well. Pasted string will not be displayed in text field if it contains any unwanted characters.