Allow Only Alphanumeric Characters for a Uitextfield

Allow only alphanumeric characters for a UITextField

Use the UITextFieldDelegate method -textField:shouldChangeCharactersInRange:replacementString: with an NSCharacterSet containing the inverse of the characters you want to allow. For example:

// in -init, -initWithNibName:bundle:, or similar
NSCharacterSet *blockedCharacters = [[[NSCharacterSet alphanumericCharacterSet] invertedSet] retain];

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

// in -dealloc
[blockedCharacters release];

Note that you’ll need to declare that your class implements the protocol (i.e. @interface MyClass : SomeSuperclass ) and set the text field’s delegate to the instance of your class.

Only allow letters and numbers for a UITextField

If you really want to restrict user from entering special characters, then probably the best way is to use shouldChangeCharactersInRange: method

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField==YOUR_USER_NAME_TEXTFIELD || textField == YOUR_PASSWORD_TEXTFIELD)
{

NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"];
for (int i = 0; i < [string length]; i++)
{
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c])
{
return NO;
}
}

return YES;
}

return YES;
}

This will restrict the user from entering the special characters. As rmaddy pointed out, it is always good to do this kind of validation when data entry happens.

PS: Make sure you set the delegate for your textfields.

Unable to limit characters to only alphanumeric inside UITextField in iOS

You will need to loop through and return NO to the method when the character is a non-alphanumeric one. So, the code that you have should be like:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

BOOL canEdit=NO;
NSCharacterSet *myCharSet = [NSCharacterSet alphanumericCharacterSet];
for (int i = 0; i < [string length]; i++) {
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c]) {
return NO;
}
}
NSUInteger newLength = [textField.text length] + [string length] - range.length;

if (newLength > 0) {

for (int i = 0; i < [string length]; i++)
{
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c])
{
canEdit=NO;
self.myButton.enabled = NO;
}
else
{
canEdit=YES;
self.myButton.enabled = YES;
}
}

} else self.myButton.enabled = NO;


return (newLength > 50 && canEdit) ? NO : YES;
}

Allow only alpha numeric characters in UITextView

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

Test UITextField text string to only contain alphanumeric characters

Check if the inversion of your accepted set is present:

if username.text!.rangeOfCharacterFromSet(letters.invertedSet) != nil {
print("invalid")
}

letters should probably be alphanumericCharacterSet() if you want to include numbers as well.

If you want to accept underscores or more chars, you will probably have to create a character set by your own. But the inversion logic will stay the same.

validate alphanumeric value in UITextField

How about using regular expression:

-(BOOL)isAlphaNumericOnly:(NSString *)input 
{
NSString *alphaNum = @"[a-zA-Z0-9]+";
NSPredicate *regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", alphaNum];

return [regexTest evaluateWithObject:input];
}

and then use it

if([self isAlphaNumeric:str])
{
NSLog(@"IT IS ALPHA NUMERIC STRING");

}

edit
The same technique can be used to validate passwords, you need only better regex:

-(BOOL)isPasswordStrong:(NSString *)password {
/*
8-20 chars
at least one letter
at least one number OR special character
no more than 3 repeated characters
*/
NSString *strongPass= @"^(?!.*(.)\\1{3})((?=.*[\\d])(?=.*[A-Za-z])|(?=.*[^\\w\\d\\s])(?=.*[A-Za-z])).{8,20}$";;
NSPredicate *regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", strongPass];

return [regexTest evaluateWithObject:password];
}

using the regular expression you can create different rules but this can give you a headstart,

Only Alphabet and whitespace allowed in UITextField Swift

The easiest way will be to add new line to the character set like

let set = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ ")

i.e, adding white space character at the end of the included character set" "

Rather than hardcoding you can use regular expression like

   do {
let regex = try NSRegularExpression(pattern: ".*[^A-Za-z ].*", options: [])
if regex.firstMatch(in: nameValue, options: [], range: NSMakeRange(0, nameValue.characters.count)) != nil {
self.showAlert(message: "Must not contain Number in Name")

} else {

}
}
catch {

}

How I disable the alpha, alpha numeric and special character in UITextField?

Take a look at the UITextFieldDelegate protocol. There’s a method called textField:shouldChangeCharactersInRange:replacementString: where you can validate the replacement string and return NO if it falls into one of the disallowed sets. As for the validation itself, see the method rangeOfCharacterFromSet: of the NSString class and the NSCharacterSet class.



Related Topics



Leave a reply



Submit