我的iPhone应用程序中有1 UITextfield
个密码。
我想通过以下验证来验证此文本字段。
@#$%^&+=^.*(?=.{10,})(?=.*d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$
如何根据上述要求限制UITextField
?
答案 0 :(得分:25)
我就是这样做的。验证应在用户输入密码时结束时进行,而不是介于两者之间。我不会使用NSRegularExpression
。
-(void)textFieldDidEndEditing:(UITextField *)textField{
int numberofCharacters = 0;
BOOL lowerCaseLetter,upperCaseLetter,digit,specialCharacter = 0;
if([textField.text length] >= 10)
{
for (int i = 0; i < [textfield.text length]; i++)
{
unichar c = [textfield.text characterAtIndex:i];
if(!lowerCaseLetter)
{
lowerCaseLetter = [[NSCharacterSet lowercaseLetterCharacterSet] characterIsMember:c];
}
if(!upperCaseLetter)
{
upperCaseLetter = [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:c];
}
if(!digit)
{
digit = [[NSCharacterSet decimalDigitCharacterSet] characterIsMember:c];
}
if(!specialCharacter)
{
specialCharacter = [[NSCharacterSet symbolCharacterSet] characterIsMember:c];
}
}
if(specialCharacter && digit && lowerCaseLetter && upperCaseLetter)
{
//do what u want
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:@"Please Ensure that you have at least one lower case letter, one upper case letter, one digit and one special character"
delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:@"Please Enter at least 10 password"
delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
}
希望这会有所帮助......
答案 1 :(得分:15)
您也可以使用Regex
执行此操作。以下是我为您提供的一些示例:
// *** Validation for Password ***
// "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$" --> (Minimum 8 characters at least 1 Alphabet and 1 Number)
// "^(?=.*[A-Za-z])(?=.*\\d)(?=.*[$@$!%*#?&])[A-Za-z\\d$@$!%*#?&]{8,16}$" --> (Minimum 8 and Maximum 16 characters at least 1 Alphabet, 1 Number and 1 Special Character)
// "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,}$" --> (Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet and 1 Number)
// "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{8,}" --> (Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character)
// "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{8,10}" --> (Minimum 8 and Maximum 10 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character)
您可以从列表中找到第四 ,以下代码段显示了如何使用它:
-(BOOL)isValidPassword:(NSString *)passwordString
{
NSString *stricterFilterString = @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{10,}";
NSPredicate *passwordTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stricterFilterString];
return [passwordTest evaluateWithObject:passwordString];
}
使用方法:
if(![self isValidPassword:txtPassword.text]) {
/* Show alert: "Password must be minimum 10 characters,
at least 1 Uppercase Alphabet, 1 Lowercase Alphabet,
1 Number and 1 Special Character" */
}
else {
// Password is valid
}
答案 2 :(得分:7)
条件:密码应包含至少8个字符,1个大写和1个数字
Swift 3中的解决方案
您可以像这样编写字符串扩展,
extension String {
func isValidPassword() -> Bool {
let regularExpression = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{8,}"
let passwordValidation = NSPredicate.init(format: "SELF MATCHES %@", regularExpression)
return passwordValidation.evaluate(with: self)
}
}
//Example 1
var password = "@Abcdef011" //string from UITextField (Password)
password.isValidPassword() // -> true
//Example 2
var password = "Abcdef011" //string from UITextField
password.isValidPassword() // -> false
或者你可以写这样的函数,
func validate(password: String) -> Bool
{
let regularExpression = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{8,}"
let passwordValidation = NSPredicate.init(format: "SELF MATCHES %@", regularExpression)
return passwordValidation.evaluate(with: password)
}
这会给你相同的结果。
答案 3 :(得分:6)
您可以使用以下函数验证密码验证,只需传递密码字符串,这将返回BOOL值。
-(BOOL) isPasswordValid:(NSString *)pwd {
NSCharacterSet *upperCaseChars = [NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLKMNOPQRSTUVWXYZ"];
NSCharacterSet *lowerCaseChars = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyz"];
//NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
if ( [pwd length]<6 || [pwd length]>20 )
return NO; // too long or too short
NSRange rang;
rang = [pwd rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
if ( !rang.length )
return NO; // no letter
rang = [pwd rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]];
if ( !rang.length )
return NO; // no number;
rang = [pwd rangeOfCharacterFromSet:upperCaseChars];
if ( !rang.length )
return NO; // no uppercase letter;
rang = [pwd rangeOfCharacterFromSet:lowerCaseChars];
if ( !rang.length )
return NO; // no lowerCase Chars;
return YES;
}
答案 4 :(得分:4)
Swift 3
检查密码是否强大?
特殊字符,如!@#$%^&amp; *()_- +是可选的
为什么我不使用正则表达式?
因为很难在常规中支持保留字符 表达式语法。
func isValidated(_ password: String) -> Bool {
var lowerCaseLetter: Bool = false
var upperCaseLetter: Bool = false
var digit: Bool = false
var specialCharacter: Bool = false
if password.characters.count >= 8 {
for char in password.unicodeScalars {
if !lowerCaseLetter {
lowerCaseLetter = CharacterSet.lowercaseLetters.contains(char)
}
if !upperCaseLetter {
upperCaseLetter = CharacterSet.uppercaseLetters.contains(char)
}
if !digit {
digit = CharacterSet.decimalDigits.contains(char)
}
if !specialCharacter {
specialCharacter = CharacterSet.punctuationCharacters.contains(char)
}
}
if specialCharacter || (digit && lowerCaseLetter && upperCaseLetter) {
//do what u want
return true
}
else {
return false
}
}
return false
}
let isVaildPass:Bool = isValidated("Test**00+-")
print(isVaildPass)
答案 5 :(得分:2)
使用正则表达式(NSRegularExpression类有关于如何编写模式本身的文档)然后:
- (BOOL)textField:(UITextField *)theTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//delete
if (string.length == 0) {
return YES;
}
if (self.regEx) {
NSMutableString* check = [NSMutableString stringWithString:theTextField.text];
[check replaceCharactersInRange:range withString:string];
NSTextCheckingResult* match = [self.regEx firstMatchInString:check options:0 range:NSMakeRange(0, [check length])];
if (match.range.length != check.length) {
return NO;
}
}
}
警告:以这种方式限制输入对用户来说确实很困惑。您输入并输入类型,而您输入的字符不会出现!
我可能会选择测试区旁边的小红色(!),但我总是允许输入!
答案 6 :(得分:2)
我有一个优雅的表格(如注册)解决方案,你有很多验证
我在我的自定义UITextField中有出口:
@IBInspectable var regexpValidation: String? = nil
在故事板中,我可以通过属性检查器访问它并将regexp字符串放入(对于电子邮件):
[a-z0-9!#$%&'*+/=?^_
{|}〜 - ] +(?:!?[A-Z0-9#$%&安培;'* + / = ^ _ {|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
然后在我的子类中我有这个计算的var:
@IBInspectable var regexpValidation:String? = nil //可选,在InterfaceBuilder中设置
var inputIsValid: Bool {
get {
if let expr = regexpValidation {
return (text.rangeOfString(expr, options: NSStringCompareOptions.RegularExpressionSearch, range: nil, locale: nil) != nil)
} else {
return true
}
}
}
可以像这样使用:
override func resignFirstResponder() -> Bool {
if (inputIsValid) {
return super.resignFirstResponder()
}
else {
text = ""
return false
}
}
答案 7 :(得分:2)
对我来说最好的方法是使用NSPredicate
和正则表达式。
这是你的案例的正则表达式:^(?=.{10,})(?=.*[0-9])(?=.*[a-zA-Z])([@#$%^&=a-zA-Z0-9_-]+)$
目标C代码:
NSString *regex = @"^(?=.{10,})(?=.*[0-9])(?=.*[a-zA-Z])([@#$%^&=a-zA-Z0-9_-]+)$";
NSPredicate *passwordTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
BOOL isValid = [passwordTest evaluateWithObject:yourTextfield.text];
答案 8 :(得分:1)
您需要使用UITextField
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
您可能希望参考实施的链接很少
答案 9 :(得分:1)
使用control:isValidObject:
协议的NSTextFieldDelegate
方法,该方法允许您验证NSTextField的值。假设您已正确配置了所有接口构建器位和部分,您可以执行以下操作:
@interface PreferencesController : NSWindowController <NSTextFieldDelegate> {
IBOutlet NSTextField *username, *password;
}
@end
@implementation PreferencesController
- (BOOL)control:(NSControl *)control isValidObject:(id)object
{
if (control == password) {
// Perform validation and return YES or NO
}
return YES;
}
@end
答案 10 :(得分:1)
SWIFT 5使用RXSWIFT,这是一种更好,整洁且反应迅速的方法。
验证密码功能将如下所示。很明显,您可以根据需要添加任意多个条件。
func validatePassword(password: String) -> (Bool, String) {
//Minimum 8 characters at least 1 Alphabet and 1 Number:
var tuple: (Bool, String) = (true, "")
var string = "Requires atleast"
if(password.rangeOfCharacter(from: CharacterSet.letters) == nil){
string = "uppercase"
tuple = (false, string)
}
if(password.rangeOfCharacter(from: CharacterSet.decimalDigits) == nil){
string += ", number"
tuple = (false, string)
}
if(password.count < 8 ){
string += ", 8 chars"
tuple = (false, string)
}
return tuple }
func isPasswordValid(in string: String) -> Observable<(Bool, String)> {
return Observable.create { observer -> Disposable in
let tuple = self.validation.validatePasswordForSymbol(password: string)
observer.onNext(tuple)
return Disposables.create()
}
}
您可以根据您的体系结构在viewModel或VC中使用上述功能。 然后在您的VC中调用以下相同的函数。
passwordTextField.rx.text
.orEmpty //1
.filter { $0.count >= 1 } //2
.flatMap { self.isPasswordValid(in: $0) }
.subscribe(onNext: { result in
print("Valid password", result)
//update UI here
// result will be like (false, "Requires atleast, 8 chars, number")
}).disposed(by: disposeBag)