How to know if a UITextField in iOS has blank spaces - iphone

I have a UITextField where user can enter a name and save it. But, user should not be allowed to enter blank spaces in the textFiled.
1 - How can I find out,if user has entered two blank spaces or complete blank spaces in the textFiled
2 - How can i know if the textFiled is filled only with blank spaces
edit - It is invalid to enter only white spaces(blank spaces)

You can "trim" the text, that is remove all the whitespace at the start and end. If all that's left is an empty string, then only whitespace (or nothing) was entered.
NSString *rawString = [textField text];
NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *trimmed = [rawString stringByTrimmingCharactersInSet:whitespace];
if ([trimmed length] == 0) {
// Text was empty or only whitespace.
}
If you want to check whether there is any whitespace (anywhere in the text), you can do it like this:
NSRange range = [rawString rangeOfCharacterFromSet:whitespace];
if (range.location != NSNotFound) {
// There is whitespace.
}
If you want to prevent the user from entering whitespace at all, see #Hanon's solution.

if you really want to 'restrict' user from entering white space
you can implement the following method in UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string];
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
if ([resultingString rangeOfCharacterFromSet:whitespaceSet].location == NSNotFound) {
return YES;
} else {
return NO;
}
}
If user enter space in the field, there is no change in the current text

Use following lines of code
NSString *str_test = #"Example ";
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
if([str_test rangeOfCharacterFromSet:whitespaceSet].location!=NSNotFound)
{
NSLog(#"Found");
}
if you want to restrict user use below code
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([string isEqualToString:#" "])
{
return NO
}
else
{
return YES
}
}

UPD: Swift 2.0 Support
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let whitespaceSet = NSCharacterSet.whitespaceCharacterSet()
let range = string.rangeOfCharacterFromSet(whitespaceSet)
if let _ = range {
return false
}
else {
return true
}
}

I had a same condition not allowing user to input blank field
Here is my code and check statement
- (IBAction)acceptButtonClicked:(UIButton *)sender {
if ([self textFieldBlankorNot:fullNametext]) {
fullNametext.text=#"na";
}
// saving value to dictionary and sending to server
}
-(BOOL)textFieldBlankorNot:(UITextField *)textfield{
NSString *rawString = [textfield text];
NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *trimmed = [rawString stringByTrimmingCharactersInSet:whitespace];
if ([trimmed length] == 0)
return YES;
else
return NO;
}

Heres Swift 3 version
let whitespaceSet = NSCharacterSet.whitespaces
let range = string.rangeOfCharacter(from: whitespaceSet)
if let _ = range {
return false
}
else {
return true
}

In Swift,
if you want to restrict the user, you can use contains()
For Example,
if userTextField.text!.contains(" "){
//your code here.....
}

Here's what I did using stringByReplacingOccurrencesOfString.
- (BOOL)validateFields
{
NSString *temp = [textField.text stringByReplacingOccurrencesOfString:#" "
withString:#""
options:NSLiteralSearch
range:NSMakeRange(0, textField.text.length)];
if ([temp length] == 0) {
// Alert view with message #"Please enter something."
return NO;
}
}

#Hanon's answer is the pretty neat, but what I needed was to allow at least 1 white space, so based on Hanon's solution I made this one:
I declared a local variable called whitespaceCount to keep the counts of the white spaces.
Hope this helps anybody!
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
if ([string rangeOfCharacterFromSet:whitespaceSet].location != NSNotFound)
{
whitespaceCount++;
if (whitespaceCount > 1)
{
return NO;
}
}
else
{
whitespaceCount = 0;
return YES;
}
}

Related

Limiting the user to enter the characters and also to convert the each entered letter into capital letter in ios

I am having 4 text fields in which I want to put two limitations simultaneously. One is that the user should be able to type in only capital letters with the maximum character limit to 2 only. My code for this is as follows:-
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
// Below logic is for All 4 Modifer Textfields
// we are restrict the user to enter only max 2 characters in modifier textfields.
if (textField==txt_modifier1 || textField==txt_modifier2 || textField==txt_modifier3 ||
textField==txt_modifier4) {
textField.text = [textField.text stringByReplacingCharactersInRange:range
withString:[string
uppercaseStringWithLocale:[NSLocale currentLocale]]];
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 2) ? NO : YES;
}
return YES;
}
this is not functioning properly as it is appending one more character as I type in any character and also not limiting the number of characters to 2. Please suggest a way to tackle this problem.
You're manually updating the text in your textfield and then sending YES back (which then appends the characters a second time). Then, you're usingthe new text with the replacement string to compare it to two (which, then appends your characters again) ...
Try this:
if (...) {
NSString *result = [textField.text stringByReplacingCharactersInRange:range
withString:string.uppercaseString];
if (result.length <= 2)
textField.text = result;
return NO;
}
return YES;
For limiting the number of characters and capitalizing it in your UITextField, use this code block
-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
textField.text = [textField.text capitalizedString];
if(textField.text.length >= 3 && range.length == 0)
{
return NO;
}
else
{
return YES;
}
Please try to use this one ...It may help you
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([string isEqualToString:[string capitalizedString]])
{
NSString *result = [textField.text stringByReplacingCharactersInRange:range
withString:string.uppercaseString];
if (result.length <= 2)
textField.text = result;
return NO;
}
else
return YES;
}
loginUITextFieldTextDidChangeNotificationMake judgment here
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(textChanged:)
name:UITextFieldTextDidChangeNotification
object:YOUR_TEXT_FIELD];
-(void)textChanged:(NSNotification *)notif {
//to do your logic
}

UILabel have to access keyboard alphabets only

can anyone tell how to access only alphabets through keyboard. Numbers and special characters should not de entered into the UILabel.
I'am new to iOS programming and I'am searching this from last 2 hours of no use. Help me out of this
try this ...
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
{
static NSCharacterSet *charSet2 = nil;
if(textField==txtfirstname)
{
if(!charSet2)
{
charSet2 = [[NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "] invertedSet];
}
NSRange location = [string rangeOfCharacterFromSet:charSet2];
return (location.location == NSNotFound);
}
}
Hope this helps...
To get a notification you'll have to use the delegate function of UITextField. If you use the UILabel. You might have to go ahead and use the Keyboard notifications. Instead what you can do is use the UITextField. You can use the UITextField border style property to make it look a like UILabel.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
for (int i = 0; i < [string length]; i++)
{
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c])
{
return YES;
}
else
{
return NO;
}
}
}

UITextField restriction-iphone

I'm having 4 textfields in my application
1.username
2.Email
3.Age
4.Password
User names are 3-25 characters and contain only the characters [a-z0-9]
Age must be between 1-100 inclusive.
Passwords are between 4-12 characters and use only the characters [a-zA-Z0-9]
how can i restrict the textfield with above requirements
please anyone help me out to do this..
Thank you for your effort and consideration.
You can use the methods in the UITextFieldDelegate protocol to validate your fields' content.
More concretely, either you use:
– textFieldShouldEndEditing:
- textFieldShouldReturn:
or you can use:
- textField:shouldChangeCharactersInRange:replacementString:
In the first case, you only validate when the user ends editing the text field; in the second case, you can do the validation at each keystroke.
In all of those methods, you receive an argument textField which you can access like this:
NSString* text = textField.text;
NSUInterger length = [text length];
if (length.....) {
// -- show alert or whatever
return NO;
}
You can validate numbers as the user type by implementing -[UITextField textField:shouldChangeCharactersInRange:replacementString:] method. Do note that this method is called before the change is made, so you need to construct the text that could be the result of the users actions yourself. For example:
-(BOOL)textField:(UITextField*)textField: shouldChangeCharactersInRange:(NSRange*)range
replacementString:(NSString*)string;
{
NSString* text = [textField.text stringByReplacingCharactersInRange:range
withString:string];
// text is now the potential string you should check against.
}
What you do from there is up to your own. Some examples could be:
// Too short?
if ([text length] < 4) ...
// Invalid character?
NSCharacterSet* invalidChars = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
if ([text rangeOfCharacterInSet:invalidChars].location != NSNotFound) ...
For more complex number validation I would use NSNumberFormatter, that has support for validating ranges and more.
You can use UITextFieldDelegate to get done what you want. Assign different values to textfield.tag for each field in - (void)viewDidLoad method and match those tag values to find the relevant field in the (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string.
#define USERNAME_FIELD_TAG 1
#define PASSWORD_FIELD_TAG 2
#define EMAIL_FIELD_TAG 3
#define AGE_FIELD_TAG 4
#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField.tab == USERNAME_FIELD_TAG)
{
if([[NSPredicate predicateWithFormat:#"SELF MATCHES[cd] %#", #"[a-z0-9]{3,35}"] evaluateWithObject:string] == FALSE)
{
textField.text = [textField.text stringByReplacingOccurrencesOfString:string withString:#"" options:NSCaseInsensitiveSearch range:range];
[self selectTextForInput:textField atRange:range];
return NO;
}
}
else if (textField.tab == PASSWORD_FIELD_TAG)
{
if([[NSPredicate predicateWithFormat:#"SELF MATCHES[cd] %#", #"[a-zA-Z0-9]{4,12}"] evaluateWithObject:string] == FALSE)
{
textField.text = [textField.text stringByReplacingOccurrencesOfString:string withString:#"" options:NSCaseInsensitiveSearch range:range];
[self selectTextForInput:textField atRange:range];
return NO;
}
}
else if (textField.tab == EMAIL_FIELD_TAG)
{
if([[NSPredicate predicateWithFormat:#"SELF MATCHES[cd] %#", #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"] evaluateWithObject:string] == FALSE)
{
textField.text = [textField.text stringByReplacingOccurrencesOfString:string withString:#"" options:NSCaseInsensitiveSearch range:range];
[self selectTextForInput:textField atRange:range];
return NO;
}
}
else if (textField.tab == AGE_FIELD_TAG)
{
if([[NSPredicate predicateWithFormat:#"SELF MATCHES[cd] %#", #"[1-100]"] evaluateWithObject:string] == FALSE)
{
textField.text = [textField.text stringByReplacingOccurrencesOfString:string withString:#"" options:NSCaseInsensitiveSearch range:range];
[self selectTextForInput:textField atRange:range];
return NO;
}
}
return YES;
}
// place the cursor at given possition
-(void)selectTextForInput:(UITextField *)input atRange:(NSRange)range {
UITextPosition *start = [input positionFromPosition:[input beginningOfDocument]
offset:range.location];
UITextPosition *end = [input positionFromPosition:start
offset:range.length];
[input setSelectedTextRange:[input textRangeFromPosition:start toPosition:end]];
}

How to disable letter characters in UITextField?

In my application i need to allow users input only numbers.
How can i allow UITextField to receive only numbers from user?
The characters in this examples are allowed, so if you dont want the user to use a character, exclude it from myCharSet.
- (BOOL)textField:(UITextField *)theTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
for (int i = 0; i < [string length]; i++) {
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c]) {
return NO;
}
}
return YES;
}
I prefer the following solution that actually prevents any any input except from numbers and backspace. Backspace for some reason is represented by an empty string and could not be used unless empty string returns YES. I also popup an alert view when the user enters a character other that numbers.
- (BOOL)textField:(UITextField *)theTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (string.length == 0) {
return YES;
}
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
for (int i = 0; i < [string length]; i++) {
unichar c = [string characterAtIndex:i];
if ([myCharSet characterIsMember:c]) {
return YES;
}
}
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"Invalid Input" message:#"Only numbers are allowed for participant number." delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[av show];
return NO;
}
This is perhaps the cleanest, simplest solution to allow only positive or negative numbers. This also allows backspace.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSCharacterSet *allowedCharacters = [NSCharacterSet characterSetWithCharactersInString:#"-0123456789"];
if([string rangeOfCharacterFromSet:allowedCharacters.invertedSet].location == NSNotFound){
return YES;
}
return NO;
}
One thing you can do is to show the numbers key pad and beside text field or some where else add a dynamic button to hide the keyboard.
you guys might flame.. but this worked for me.. only numbers (including negatives), and backspace.
NSCharacterSet *validCharSet;
if (range.location == 0)
validCharSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789-."];
else
validCharSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789."];
if ([[string stringByTrimmingCharactersInSet:validCharSet] length] > 0 ) return NO; //not allowable char
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber* candidateNumber;
NSString* candidateString = [textField.text stringByReplacingCharactersInRange:range withString:string];
range = NSMakeRange(0, [candidateString length]);
[numberFormatter getObjectValue:&candidateNumber forString:candidateString range:&range error:nil];
if (candidateNumber == nil ) {
if (candidateString.length <= 1)
return YES;
else
return NO;
}
return YES;
Here is my solution applying algebra of sets with the method isSupersetOfSet: This also doesn't allow pasting text with invalid characters:
- (BOOL)textField:(UITextField *)theTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (string.length == 0 || [_numericCharSet isSupersetOfSet:[NSCharacterSet characterSetWithCharactersInString:string]]) {
return YES;
}
else {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"Invalid Input"
message:#"Only numeric input allowed."
delegate:self
cancelButtonTitle:#"Close"
otherButtonTitles:nil];
[av show];
return NO;
}
}
Note: according to Apple Developer Library, It's preferable cache the static NSCharacterSet than to create it again and again (here _numericCharSet).
However I prefer to let the user to input any character and validate the value in the method textFieldShouldEndEditing: called when the textField tries to resign first responder.
In this manner the user can paste any text (maybe composed with a mix of letters and numbers) and tidy up it in my textFields. The users do not like to see limited their actions.
In Swift
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if textField.tag == 2 { //your textField
let invalid = NSCharacterSet(charactersInString: "aeiou") //characters to block
if let range = string.rangeOfCharacterFromSet(invalid) {
return false
}
}
return true
}
Here is a swift example
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
var disabledCharacters:NSCharacterSet = NSCharacterSet(charactersInString: "0123456789")
for (var i:Int = 0; i < count(string); ++i) {
var c = (string as NSString).characterAtIndex(i)
if (disabledCharacters.characterIsMember(c)) {
println("Can't use that character dude :/")
return false
}
}
return true
}
Don't forget to add UITextFieldDelegate to your UIViewController as well.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
char *x = (char*)[string UTF8String];
//NSLog(#"char index is %i",x[0]);
if([string isEqualToString:#"-"] || [string isEqualToString:#"("] || [string isEqualToString:#")"] || [string isEqualToString:#"0"] || [string isEqualToString:#"1"] || [string isEqualToString:#"2"] || [string isEqualToString:#"3"] || [string isEqualToString:#"4"] || [string isEqualToString:#"5"] || [string isEqualToString:#"6"] || [string isEqualToString:#"7"] || [string isEqualToString:#"8"] || [string isEqualToString:#"9"] || x[0]==0 || [string isEqualToString:#" "]) {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 14) ? NO : YES;
} else {
return NO;
}
}
This thread is a little old, but for the sake of reference I am going to leave a solution in swift 3. This solution will combine decimalDigits and the actual decimal. You can put together whatever combination you'd like, but for my case this is what the requirements were.
// instantiate a mutable character set
let characterSet = NSMutableCharacterSet()
// assign the needed character set
characterSet.formUnion(with: NSCharacterSet.decimalDigits)
// only need the decimal character added to the character set
characterSet.addCharacters(in: ".")
// invert and return false if it's anything other than what we're looking for
if string.rangeOfCharacter(from: characterSet.inverted) != nil {
return false
}

Validate against empty UITextField?

What is the value of a UITextField when it is empty? I can't seem to get this right.
I've tried (where `phraseBox' it the name of the said UITextField
if(phraseBox.text != #""){
and
if(phraseBox.text != nil){
What am I missing?
// Check to see if it's blank
if([phraseBox.text isEqualToString:#""]) {
// There's no text in the box.
}
// Check to see if it's NOT blank
if(![phraseBox.text isEqualToString:#""]) {
// There's text in the box.
}
found this at apple discussions when searching for the same thing,thought ill post it here too.
check the length of the string :
NSString *value = textField.text;
if([value length] == 0) {
}
or optionally trim whitespaces from it before validation,so user cannot enter spaces instead.works well for usernames.
NSString *value = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if([value length] == 0) {
// Alert the user they forgot something
}
Try following code
textField.text is a string value so we are checking it like this
if([txtPhraseBox.text isEqualToString:#""])
{
// There's no text in the box.
}
else
{
NSLog(#"Text Field Text == : %# ",txtPhraseBox.text);
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSString *fullText = [textField.text stringByAppendingString:string];
if ((range.location == 0) && [self isABackSpace:string]) {
//the textFiled will be empty
}
return YES;
}
-(BOOL)isABackSpace:(NSString*)string {
NSString* check =#"Check";
check = [check stringByAppendingString:string];
if ([check isEqualToString:#"Check"]) {
return YES;
}
return NO;
}
Use for text field validation:
-(BOOL)validation{
if ([emailtextfield.text length] <= 0) {
[UIAlertView showAlertViewWithTitle:AlertTitle message:AlertWhenemailblank];
return NO; }
return YES;}
Actually, I ran into slight problems using Raphael's approach with multiple text fields. Here's what I came up with:
if ((usernameTextField.text.length > 0) && (passwordTextField.text.length > 0)) {
loginButton.enabled = YES;
} else {
loginButton.enabled = NO;
}
Validation against empty UITextfield. if you don't want that UITextField should not accept blank white spaces. Use this code snippet:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string];
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
if ([resultingString rangeOfCharacterFromSet:whitespaceSet].location == NSNotFound) {
return YES;
} else {
return NO;
}
}