Validate against empty UITextField? - iphone

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;
}
}

Related

How to Append a Special Character after every 3 characters in UITextField Ex: (123-12346) like '-' i did it but issue while Clear

I am getting Phone card number form user in UI text field. The format of number is like
123-4567-890
I want that as user types 123 automatically - is inserted in UITextField same after 4567 - and so on.
I Did it using following code in UITextField delegate method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
NSLog(#"***** %d",textField.text.length);
if(textField.text.length == 3)
{
textField.text = [textField.text stringByAppendingString:#"-"];
}
return YES;
}
But the Problem raised while clear the text, When we start clearing.
Last 3 digits 890 clears and then - addded, we cleared it and again added and soooo on so clearing stop at
We clear all the text at a time using
textField.clearButtonMode = UITextFieldViewModeWhileEditing; //To clear all text at a time
But our requirement is user must delete one character at a time.
How to achieve it?
During clearing replacementString should be empty #"". So replacement string should be checked also in addition to length check. Like this:
if (textField.text.length == 3 && ![string isEqualToString:#""]) {
// append -
}
USE: I have seen this somewhere in this forum, It worked for me
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *filter = #"###-####-###";
if(!filter) return YES;
NSString *changedString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if(range.length == 1 && string.length < range.length && [[textField.text substringWithRange:range] rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:#"0123456789"]].location == NSNotFound)
{
NSInteger location = changedString.length-1;
if(location > 0)
{
for(; location > 0; location--)
{
if(isdigit([changedString characterAtIndex:location]))
break;
}
changedString = [changedString substringToIndex:location];
}
}
textField.text = filteredStringFromStringWithFilter(changedString, filter);
return NO;
}
NSString *filteredStringFromStringWithFilter(NSString *string, NSString *filter)
{
NSUInteger onOriginal = 0, onFilter = 0, onOutput = 0;
char outputString[([filter length])];
BOOL done = NO;
while(onFilter < [filter length] && !done)
{
char filterChar = [filter characterAtIndex:onFilter];
char originalChar = onOriginal >= string.length ? '\0' : [string characterAtIndex:onOriginal];
switch (filterChar) {
case '#':
if(originalChar=='\0')
{
done = YES;
break;
}
if(isdigit(originalChar))
{
outputString[onOutput] = originalChar;
onOriginal++;
onFilter++;
onOutput++;
}
else
{
onOriginal++;
}
break;
default:
outputString[onOutput] = filterChar;
onOutput++;
onFilter++;
if(originalChar == filterChar)
onOriginal++;
break;
}
}
outputString[onOutput] = '\0';
return [NSString stringWithUTF8String:outputString];
}

How to know if a UITextField in iOS has blank spaces

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;
}
}

iOS TextField Validation

I need a way to ensure that phone numbers have 10 digits with no other characters ie () - and make sure that email addresses are valid emails (formatted correctly).
Is there any library that can't make this easy for me so I don't have to write regular expressions.
This will check a UITextField for a proper email and phone number of 10 digits or less.
Add this method to the textFields delegate then check if the characters it is about to change should be added or not.
Return YES or NO depending on the text field, how many characters are currently in it, and what characters it wants to add:
#define ALPHA #"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
#define NUMERIC #"1234567890"
#define ALPHA_NUMERIC ALPHA NUMERIC
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *unacceptedInput = nil;
switch (textField.tag) {
// Assuming EMAIL_TextField.tag == 1001
case 1001:
if ([[textField.text componentsSeparatedByString:#"#"] count] > 1)
unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:#".-"]] invertedSet];
else
unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:#".!#$%&'*+-/=?^_`{|}~#"]] invertedSet];
break;
// Assuming PHONE_textField.tag == 1002
case 1002:
if (textField.text.length + string.length > 10) {
return NO;
}
unacceptedInput = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
break;
default:
unacceptedInput = [[NSCharacterSet illegalCharacterSet] invertedSet];
break;
}
return ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] <= 1);
}
Also, check out these 2 articles:
Auto-formatting phone number UITextField on the iPhone
PhoneNumberFormatter.
Here's a simple way of ensuring phonenumber length in the UIViewController that has the text field in it's view.
- (void)valueChanged:(id)sender
{
if ([[[self phoneNumberField] text] length] > 10) {
[[self phoneNumberField] setText:[[[self phoneNumberField] text]
substringToIndex:10]];
}
}
- (void) viewWillAppear:(BOOL)animated
{
[[self phoneNumberField] addTarget:self
action:#selector(valueChanged:)
forControlEvents:UIControlEventEditingChanged];
}
For emails I suppose you want to check against a regexp when it loses focus.
Here's Simple Example for UITextField Validation while type in keyboard other characters not displaying
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
//UITextField *tf_phonenumber,*tf_userid;
if (textField.text<=10) {
char c=*[string UTF8String];
if (tf_phonenumber==textField) //PhoneNumber /Mobile Number
{
if ((c>='0' && c<='9')||(c==nil)) {
return YES;
}
else
return NO;
}
if (tf_userid==textField) //UserID validation
{
if ((c>='a' && c<='z')||(c>='A' && c<='Z')||(c==' ')||(c==nil)) {
return YES;
}
else
return NO;
}
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 can i display mobile number in 123-456-7890 format in textfield

i need to enter mobile number in a text field.
i need to display mobile number like this format 123-456-7890.
for eg: 1234567890 is my mobile number,while am entering this mobile number in text field,
for first 3 digits i need to place -,after 3 digits again i need to place -.
if i enter 123 then automatically place - in text field,after 456 place ,no need of placing for further 4 digits.
similar to displaying text in currency format.
but while getting text from that text field i need to get mobile number no need of - like 1234567890,not 123-456-7890.
i think my question is quite clear now,let me add comment if is not.
Thank u in advance.
Just to clarify: As a user enters a phone number into a UITextField, you would like it to automatically insert dashes in the proper places.
The answer is in using the UITextFieldDelegate protocol.
1) Set your controller object as a delegate for the UITextField.
2) You'll find the following method in the protocol:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
This method is called every time a character change occurs in the text field.
3) How robust you want your implementation to be is up to you. You could simply do a count of the current characters and insert dashes after 3 and 6 characters. It would be wise to also reject any non-numeric characters.
Here is a sample implementation. We basically take over the field editing manually - Inserting dashes after the appropriate string lengths and making sure the user can only enter numbers:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *numSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789-"];
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
int charCount = [newString length];
if ([newString rangeOfCharacterFromSet:[numSet invertedSet]].location != NSNotFound
|| [string rangeOfString:#"-"].location != NSNotFound
|| charCount > 12) {
return NO;
}
if (charCount == 3 || charCount == 7) {
newString = [newString stringByAppendingString:#"-"];
}
textField.text = newString;
return NO;
}
Updated Matthew McGoogan's code : This works fine with back space also..
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (textField.tag == 8) {
NSCharacterSet *numSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789-"];
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
int charCount = [newString length];
if (charCount == 3 || charCount == 7) {
if ([string isEqualToString:#""]){
return YES;
}else{
newString = [newString stringByAppendingString:#"-"];
}
}
if (charCount == 4 || charCount == 8) {
if (![string isEqualToString:#"-"]){
newString = [newString substringToIndex:[newString length]-1];
newString = [newString stringByAppendingString:#"-"];
}
}
if ([newString rangeOfCharacterFromSet:[numSet invertedSet]].location != NSNotFound
|| [string rangeOfString:#"-"].location != NSNotFound
|| charCount > 12) {
return NO;
}
textField.text = newString;
return NO;
}
return YES;}
I used Matthews post above as a base.
This will format as so: (444) 444-4444
It also handles backspaces, unlike the answer above.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if(textField == _txtPhone1 || textField == _txtPhone2 || textField == _txtPhone3 || textField == _txtPhone4)
{
NSCharacterSet *numSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789-() "];
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
int charCount = [newString length];
if ([newString rangeOfCharacterFromSet:[numSet invertedSet]].location != NSNotFound
|| [string rangeOfString:#")"].location != NSNotFound
|| [string rangeOfString:#"("].location != NSNotFound
|| [string rangeOfString:#"-"].location != NSNotFound
|| charCount > 14) {
return NO;
}
if (![string isEqualToString:#""])
{
if (charCount == 1)
{
newString = [NSString stringWithFormat:#"(%#", newString];
}
else if(charCount == 4)
{
newString = [newString stringByAppendingString:#") "];
}
else if(charCount == 5)
{
newString = [NSString stringWithFormat:#"%#) %#", [newString substringToIndex:4], [newString substringFromIndex:4]];
}
else if(charCount == 6)
{
newString = [NSString stringWithFormat:#"%# %#", [newString substringToIndex:5], [newString substringFromIndex:5]];
}
else if (charCount == 9)
{
newString = [newString stringByAppendingString:#"-"];
}
else if(charCount == 10)
{
newString = [NSString stringWithFormat:#"%#-%#", [newString substringToIndex:9], [newString substringFromIndex:9]];
}
}
textField.text = newString;
return NO;
}
}
Use
NSString* number = [textField.text stringByReplacingOccurrencesOfString: #"-" withString: #""];