如何验证字符串是否为字母数字

时间:2021-02-22 19:20:43

It might look simple but I cannot find a solution for this. In my application, I have many UITextFields. For example, let's say I have a UITextField called textField. When I enter a string into textField, I should validate whether string is alphanumeric. How can I do this?

它可能看起来很简单,但我无法找到解决方案。在我的应用程序中,我有许多UITextFields。例如,假设我有一个名为textField的UITextField。当我在textField中输入一个字符串时,我应该验证字符串是否是字母数字。我怎样才能做到这一点?

I also have a button, apart from textField. After entering into textField, when I press button, I should validate whether the entered string is alphanumeric by showing it with NSLog. So can anyone help me solving this with some example or sample code?

除了textField之外,我还有一个按钮。进入textField后,当我按下按钮时,我应该通过显示NSLog来验证输入的字符串是否是字母数字。那么有人可以通过一些示例或示例代码帮我解决这个问题吗?

2 个解决方案

#1


5  

You can try following-

你可以试试以下 -

NSString *string = myTextField.text;
NSCharacterSet *alphanumericSet = [NSCharacterSet alphanumericCharacterSet];
NSCharacterSet *numberSet = [NSCharacterSet decimalDigitCharacterSet];
BOOL isAplhaNumericOnly= [[string stringByTrimmingCharactersInSet:alphanumericSet] isEqualToString:@""] && ![[string stringByTrimmingCharactersInSet:numberSet] isEqualToString:@""];

This bool will return true only if your string is alphanumeric and not numeric only.

只有当您的字符串是字母数字而不是数字时,此bool才会返回true。

EDITED:-

To Log bool-

记录bool-

NSLog(@"isAplhaNumericOnly: %d",isAplhaNumericOnly);

And to return from this function -

并从这个功能返回 -

if(isAplhaNumericOnly) {
    return;
}

Also if you want to show some alert then you can write code for presenting the alert above return statement.

此外,如果您想显示一些警报,那么您可以编写代码以显示返回语句上方的警报。

#2


1  

You can NSLog BOOL values like this.

您可以像这样使用NSLog BOOL值。

NSLog(@"Bool Value: %@",(isAplhaNumericOnly?@"YES":@"NO"));

#1


5  

You can try following-

你可以试试以下 -

NSString *string = myTextField.text;
NSCharacterSet *alphanumericSet = [NSCharacterSet alphanumericCharacterSet];
NSCharacterSet *numberSet = [NSCharacterSet decimalDigitCharacterSet];
BOOL isAplhaNumericOnly= [[string stringByTrimmingCharactersInSet:alphanumericSet] isEqualToString:@""] && ![[string stringByTrimmingCharactersInSet:numberSet] isEqualToString:@""];

This bool will return true only if your string is alphanumeric and not numeric only.

只有当您的字符串是字母数字而不是数字时,此bool才会返回true。

EDITED:-

To Log bool-

记录bool-

NSLog(@"isAplhaNumericOnly: %d",isAplhaNumericOnly);

And to return from this function -

并从这个功能返回 -

if(isAplhaNumericOnly) {
    return;
}

Also if you want to show some alert then you can write code for presenting the alert above return statement.

此外,如果您想显示一些警报,那么您可以编写代码以显示返回语句上方的警报。

#2


1  

You can NSLog BOOL values like this.

您可以像这样使用NSLog BOOL值。

NSLog(@"Bool Value: %@",(isAplhaNumericOnly?@"YES":@"NO"));