How to disable letter characters in UITextField? - iphone

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
}

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 perform validation on textfield for phone number entered by user in iPhone?

I have an application where I have I a textfield where user enters his mobile number including his country code. The format of the mobile number to be entered is +91-9884715715. When the user enters his/her mobile number initially validation should be performed that the first value entered by user is '+' and then the number that is entered after + should not be less that 0.
But after this I am getting confused that how to get the number of numbers entered between + and -, because user enters the country code and the length of numbers entered between + and - must be dynamic not static.
Try this ., might help you
- (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:
(NSString *)string {
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (textField == self.yourphoneNumberfield) {
NSArray *sep = [newString componentsSeparatedByString:#"-"];
if([sep count] >= 2)
{
countryCode = [NSString stringWithFormat:#"%#",[sep objectAtIndex:0]];
if ([[countryCode substringToIndex:1] isEqualToString:#"+"]) {
phoneNumber = [NSString stringWithFormat:#"%#",[sep objectAtIndex:1]];
return ([countryCode length]+[phoneNumber length]);
}
}
}
return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
NSLog(#"Phone Number : %#",phoneNumber);
if (textField == self.yourphoneNumberfield) {
if ([phoneNumber length]<10)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"Please Enter a Valid Mobile number" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
return YES;
}
Try This:
NSString *code=#"+91-99999999";
NSRange rr2 = [code rangeOfString:#"+"];
NSRange rr3 = [code rangeOfString:#"-"];
int lengt = rr3.location - rr2.location - rr2.length;
int location = rr2.location + rr2.length;
NSRange aa;
aa.location = location;
aa.length = lengt;
code = [code substringWithRange:aa];
NSLog(#"%#",code);
Goto XIB interface Builder and open xib document select ur phone number type textfield and go to textfield attribute, In the Text Input Traits, select Keyboard option from Default to Phone Pad.
// limit the input to only the stuff in this character set, so no emoji or any other insane characters
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:#"1234567890"];
if ([string rangeOfCharacterFromSet:set].location == NSNotFound) {
return NO;
}
Refer #Bala's answer
NSString *call = #"+91-9884715715";
// Search for the "+a" starting at the end of string
NSRange range = [call rangeOfString:#"+" options:NSBackwardsSearch];
// What did we find
if (range.length > 0)
NSLog(#"Range is: %#", NSStringFromRange(range));
Edit
Refer following link: TextField Validation With Regular Expression
Change the line
- (BOOL)validateInputWithString:(NSString *)aString
{
NSString * const regularExpression = #"^([+]{1})([0-9]{2,6})([-]{1})([0-9]{10})$";
NSError *error = NULL;
Add the code
- (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:#"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 ) {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 18) ? NO : YES;
} else {
return NO;
}
}
Edit
Tested with demo:
//// Button Press Event
-(IBAction)Check:(id)sender{
BOOL check = [self validateInputWithString:TextField.text];
if(check == YES){
NSLog(#"Hii");
NSString *string= [NSString stringWithFormat:#"%#", TextField.text];
NSArray *first = [string componentsSeparatedByString:#"-"];
NSString *second = [first objectAtIndex:1];
NSString *third = [first objectAtIndex:0];
if([second length] < 11){
NSLog(#"bang");
}
else{
NSLog(#"Fault");
}
if([third length] > 3 || [third length] < 7){
NSLog(#"Bang");
}
else{
NSLog(#"fault");
}
}
else{
NSLog(#"FAULT");
}
}

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

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

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