【问题标题】:How to set validation in UITextFields如何在 UITextFields 中设置验证
【发布时间】:2016-07-27 08:49:38
【问题描述】:

我正在使用一些文本字段和文本字段验证。我在下面显示了我的代码,在此代码中单击按钮事件和所有文本字段文本保存在 Web 服务器上,在此代码验证中仅在空文本字段上运行。但我想更正电子邮件地址验证并修复所有文本字段字符长度。我尝试了很多次,但有些时间条件错误,有些时候不显示警报视图,有些时候不保存文本字段文本。怎么可能,请帮忙,谢谢

我的代码

- (IBAction)submit:(id)sender {

if(self.txname == nil || [self.txname.text isEqualToString:@""])
{
    UIAlertView *ErrorAlert = [[UIAlertView alloc] initWithTitle:@"Name"message:@"All Fields are mandatory." delegate:nil cancelButtonTitle:@"OK"otherButtonTitles:nil, nil];
    [ErrorAlert show];
    
}

 else if(self.txemail == nil || [self.txemail.text isEqualToString:@""])
{
    
    UIAlertView *ErrorAlert = [[UIAlertView alloc] initWithTitle:@"Email"message:@"All Fields are mandatory." delegate:nil cancelButtonTitle:@"OK"otherButtonTitles:nil, nil];
    [ErrorAlert show];
    

}

 else if(self.tx_phone == nil || [self.tx_phone.text isEqualToString:@""])
{
    UIAlertView *ErrorAlert = [[UIAlertView alloc] initWithTitle:@"Phone"message:@"All Fields are mandatory." delegate:nil cancelButtonTitle:@"OK"otherButtonTitles:nil, nil];
    [ErrorAlert show];
    
    
}
 else if(self.txcomment == nil || [self.txcomment.text isEqualToString:@""])
{
    UIAlertView *ErrorAlert = [[UIAlertView alloc] initWithTitle:@"Comment"message:@"All Fields are mandatory." delegate:nil cancelButtonTitle:@"OK"otherButtonTitles:nil, nil];
    [ErrorAlert show];
    
    
}


else
{


//Here YOUR URL
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"MY URL"]];


//create the Method "GET" or "POST"
[request setHTTPMethod:@"POST"];

//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *userUpdate =[NSString stringWithFormat:@"name=%@&email=%@&phone=%@&  comment=%@&",_txname.text,_txemail.text,_tx_phone.text,_txcomment.text,nil];



//Check The Value what we passed
NSLog(@"the data Details is =%@", userUpdate);

//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];

//Apply the data to the body
[request setHTTPBody:data1];

//Create the response and Error
NSError *err;
NSURLResponse *response;

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];

//This is for Response
NSLog(@"got response==%@", resSrt);
if(resSrt)
{
    NSLog(@"got response");
    
}
else
{
    NSLog(@"faield to connect");
}
    {
        UIAlertView *ErrorAlert = [[UIAlertView alloc] initWithTitle:@"Success"message:@"All Fields are mandatory." delegate:nil cancelButtonTitle:@"OK"otherButtonTitles:nil, nil];
        [ErrorAlert show];
        
        
    }
    [self.view endEditing:YES];
    self.txname.text=@"";
    self.txemail.text=@"";
    self.tx_phone.text=@"";
    self.txcomment.text=@"";
    
   
}
}

【问题讨论】:

    标签: ios objective-c iphone validation uitextfield


    【解决方案1】:

    喜欢

    - (IBAction)submit:(id)sender {
    
       if (![txname hasText]) {
         [self showAlertView:@"Alert" message:@"name is empty"];
       }
       else if  (![txemail hasText])
      {
        [self showAlertView:@"Alert" message:@"email is empty"];
       }
      else if ([self isValidEmailAddress:txemail.text] == NO)
      {
      [self showAlertView:@"Alert" message:@"Invaildemail"];
      }
      else
      {
      // call webservice for succes
      }
    

    创建警报控制器

    - (void)showAlertView:(NSString*)title message:(NSString*)message
    {
    UIAlertController* alertMessage = [UIAlertController
        alertControllerWithTitle:title
                         message:message
                  preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* yesButton = [UIAlertAction
        actionWithTitle:@"OK"
                  style:UIAlertActionStyleDefault
                handler:^(UIAlertAction* action){
                }];
    
    [alertMessage addAction:yesButton];
    
    [self presentViewController:alertMessage animated:YES completion:nil];
    }
    

    用于电子邮件验证

    -  (BOOL)isValidEmailAddress:(NSString *)emailAddress
    {
     //Create a regex string
    NSString *stricterFilterString = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" ;
    
    //Create predicate with format matching your regex string
    NSPredicate *emailTest = [NSPredicatepredicateWithFormat:
                              @"SELF MATCHES %@", stricterFilterString];
    
    //return true if email address is valid
    return [emailTest evaluateWithObject:emailAddress];
    }
    

    更新

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
     if (textField == self.txname)
     {
    // Prevent crashing undo bug – see note below.
    if(range.length + range.location > textField.text.length)
    {
        return NO;
    }
    
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return newLength <= 25;
    }
     return YES;
    }
    

    【讨论】:

    • @AnkurKumawat - 我使用 Dismiss 作为宏但我在这里修改为 OK 的原因,检查更新的答案
    • @AnkurKumawat - 字符长度 ..?在哪里
    • @AnkurKumawat - 这意味着你需要这个条件也正确
    • 这个时间条件是正确的,但我还包括一个字符长度固定的东西
    • @AnkurKumawat - 您的评论不清楚,请检查更新答案一次
    【解决方案2】:

    我在我的代码中做到了,喜欢以下方式:

        - (IBAction)submit:(id)sender {
    
            if (![self isFormValid]) {
    
                return;
    
            }
    
        NSError *error;
    
    
        if (!error)
        {
            UIAlertView *signupalert = [[UIAlertView alloc]initWithTitle:@"Congratulations" message:@"Record Added Successfully" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    
            [signupalert show];
    
        }
    
    }
    
    -(BOOL)isFormValid
    {
    
        NSString *emailRegEx =@"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    
        NSPredicate *emailTest =[NSPredicate predicateWithFormat:@"SELF MATCHES %@",emailRegEx];
    
    
    
        if (txname.text && txname.text.length==0)
        {
            [self showErrorMessage:@"Please enter name"];
            return NO;
        }
    
        else if (tx_phone.text && tx_phone.text.length!=10)
        {
            [self showErrorMessage:@"Please enter valid phone number"];
            return NO;
        }
    
        else if([emailTest evaluateWithObject: txemail.text]==NO)
        {
            [self showErrorMessage:@"Please enter Valid Email_id"];
            return NO;
        }
        else if (txcomment.text && txcomment.text.length==0)
        {
            [self showErrorMessage:@"Please enter comment"];
            return NO;
        }
    
        return YES;
    }
    
    -(void)showErrorMessage:(NSString *)message
    {
    
            UIAlertView *alertmessage = [[UIAlertView alloc]initWithTitle:@"Error" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    
            [alertmessage show];
    
        }
    

    【讨论】:

    • 未声明的标识符:- isFormValid
    • @Ankur 更新了我的代码中的小改动,请检查一次.. 解决您的问题.. :)
    • 它的工作。谢谢,但是名称文本字段字符长度如何设置
    • if (txname.text && txname.text.length==0) 在这里设置它兄弟@AnkurKumawat
    【解决方案3】:
       -(BOOL) NSStringIsValidEmail:(NSString *)checkEmail
     {
      BOOL stricterFilter = NO; 
      NSString *filter = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
          NSString *lstring = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
       NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
      NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
     return [emailTest evaluateWithObject:checkEmail];
     }
    

    【讨论】:

    • 你在哪里实现这个方法
    猜你喜欢
    • 1970-01-01
    • 2011-10-09
    • 2015-07-20
    • 2019-06-28
    • 1970-01-01
    • 2020-02-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    相关资源
    最近更新 更多