我正在使用Objective C创建登录屏幕,我想在其中实现用户名(电子邮件)和密码的验证。如何以非常简单的方式实现这一点。
答案 0 :(得分:10)
您始终可以使用textField shouldChangeCharactersInRange委托来处理textField中允许的字符数。看看下面提供的解决方案:)希望有所帮助
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if(textField == self.emailTextField){
if (textField.text.length < 30 || string.length == 0){
return YES;
}
else{
return NO;
}
}
}
修改强>
根据您的意见,您没有收到textField代表,所以您可以这样做:)
在ViewController中,使用
确认UITextFieldDelegateYourViewController : UIViewController <UITextFieldDelegate>
在viewDidLoad或ViewWillAppear中将textField委托设置为self。
self.emailTextField.delegate = self;
答案 1 :(得分:0)
如果单击验证按钮,设置验证按钮操作并查看以下代码,首先检查两个文本字段是否为空,如果您提供文本然后再次检查其有效的电子邮件类型,则所有条件都为真,然后把你的代码运行,
-(IBAction)action:(id)sender
{
if (tfMail.text.length == 0 || tfPass.text.length == 0)
{
[self validatetextfield];
}
else if (![tfMail.text isEqualToString:@""])
{
NSString *emailRegEx = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
//Valid email address
if ([emailTest evaluateWithObject:tfMail.text] == YES)
{
//Its validated put your success code,
}
else
{
UIAlertController *aler = [UIAlertController alertControllerWithTitle:@"Test!" message:@"Please Enter Valid Email Address. \nex. fdsjfkd@mail.com" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self dismissViewControllerAnimated:YES completion:nil];
}];
[aler addAction:action];
[self presentViewController:aler animated:YES completion:nil];
//not valid email address
}
}
}
警报消息方法:
-(void) validatetextfield
{
if (tfMail.text.length==0) {
UIAlertController *aler = [UIAlertController alertControllerWithTitle:@"Email Field Empty!" message:@"Please Enter the Email" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self dismissViewControllerAnimated:YES completion:nil];
}];
[aler addAction:action];
[self presentViewController:aler animated:YES completion:nil];
[tfMail becomeFirstResponder];
}
else if (tfPass.text.length==0)
{
UIAlertController *aler = [UIAlertController alertControllerWithTitle:@"Password Field Empty!" message:@"Please Enter the Password" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self dismissViewControllerAnimated:YES completion:nil];
}];
[aler addAction:action];
[self presentViewController:aler animated:YES completion:nil];
[tfPass becomeFirstResponder];
}
}
它成功地为我工作,希望它有所帮助。