ios - Objective-c 如何对 textField 进行验证

标签 ios objective-c validation uitextfield

我想防止用户不输入任何数据以及只输入空格。所以基本上必须至少有一个字符没有空格。然后我还想删除单词开头的所有空格,以便第一个字母是一个不是空格的字符。

编辑

用户必须输入一些东西,如果用户在它之前输入了几个空格,那么我想修剪这些空格。我还想防止用户只输入空格。

示例

如果用户输入名字和姓氏,如“James Dean”,我想去掉 James 和 Dean 之间的第一个空格,而不是第二个空格。

最佳答案

将您的 UIViewController 设置为您的目标 UITextFielddelegate 并实现此方法:

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

  // verify the text field you wanna validate
  if (textField == _nameTextField) {

    // do not allow the first character to be space | do not allow more than one space
    if ([string isEqualToString:@" "]) {
      if (!textField.text.length)
        return NO;
      if ([[textField.text stringByReplacingCharactersInRange:range withString:string] rangeOfString:@"  "].length)
        return NO;
    }

    // allow backspace
    if ([textField.text stringByReplacingCharactersInRange:range withString:string].length < textField.text.length) {
      return YES;
    }

    // in case you need to limit the max number of characters
    if ([textField.text stringByReplacingCharactersInRange:range withString:string].length > 30) {
      return NO;
    }

    // limit the input to only the stuff in this character set, so no emoji or cirylic or any other insane characters
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 "];

    if ([string rangeOfCharacterFromSet:set].location == NSNotFound) {
      return NO;
    }

  }

  return YES;
}

关于ios - Objective-c 如何对 textField 进行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15403059/

相关文章:

ios - Xcode 8 Xamarin 构建失败

ios - Storyboard中深色模式下的占位符颜色

ios - 在 Swift 编程语言中将 NSManagedObject 从一个类传递到另一个类?

javascript - 外部 javascript - 表现不佳

javascript - filter() 参数没有给出正确的输出

iphone - 与 insertSubView 的索引值混淆

ios - 一个 UIButton 上的两个控件事件

ios - 创建iOS应用的通用音频路径

iPhone 扩展音频文件服务,mp3 -> PCM -> mp3

javascript - ASP.net。服务器端验证和客户端验证完美配合的最佳方式是什么