I am creating login screen using Objective C in which i want to implement validation for User name(E-Mail) and password.How to implement this in very simple way.
You can always make use textField shouldChangeCharactersInRange delegate to handle the number of characters allowed in textField. Have look at the solution provided below :) Hope it helps
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if(textField == self.emailTextField){
if (textField.text.length < 30 || string.length == 0){
return YES;
}
else{
return NO;
}
}
}
EDIT
As per your comments you are not recieveing the textField delegates, so here is what you can do :)
In your ViewController, confirm the UITextFieldDelegate using,
YourViewController : UIViewController <UITextFieldDelegate>
In your viewDidLoad or ViewWillAppear set the textField delegate as self.
self.emailTextField.delegate = self;
If you click the Validate Button, set the validate button Action and see the below code,first check the two textfield empty or not, if you give text then again check its valid email type or not, then all conditions are true, then put your code and run,
-(IBAction)action:(id)sender
{
if (tfMail.text.length == 0 || tfPass.text.length == 0)
{
[self validatetextfield];
}
else if (![tfMail.text isEqualToString:#""])
{
NSString *emailRegEx = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegEx];
//Valid email address
if ([emailTest evaluateWithObject:tfMail.text] == YES)
{
//Its validated put your success code,
}
else
{
UIAlertController *aler = [UIAlertController alertControllerWithTitle:#"Test!" message:#"Please Enter Valid Email Address. \nex. fdsjfkd#mail.com" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self dismissViewControllerAnimated:YES completion:nil];
}];
[aler addAction:action];
[self presentViewController:aler animated:YES completion:nil];
//not valid email address
}
}
}
Alert Message Method:
-(void) validatetextfield
{
if (tfMail.text.length==0) {
UIAlertController *aler = [UIAlertController alertControllerWithTitle:#"Email Field Empty!" message:#"Please Enter the Email" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self dismissViewControllerAnimated:YES completion:nil];
}];
[aler addAction:action];
[self presentViewController:aler animated:YES completion:nil];
[tfMail becomeFirstResponder];
}
else if (tfPass.text.length==0)
{
UIAlertController *aler = [UIAlertController alertControllerWithTitle:#"Password Field Empty!" message:#"Please Enter the Password" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self dismissViewControllerAnimated:YES completion:nil];
}];
[aler addAction:action];
[self presentViewController:aler animated:YES completion:nil];
[tfPass becomeFirstResponder];
}
}
its successfully working for me, hope its helpful.
Related
I am trying to create a small app in which user need to enter the pin on the correct pin it will say correct pin else wrong but I am not sure if my logic is correct below. I am using the Xcode10 on the latest Mac version.
- (IBAction)validatePin:(id)sender {
[ViewController checkPin:self.textPin.text.integerValue];
}
+(BOOL)checkPin:(NSInteger)pin {
if (pin == 1408)
{
//[UIAlertController alertControllerWithTitle:#"Pin" message:#"Success" preferredStyle:UIAlertControllerStyleAlert];
[[UIAlertView alloc] initWithTitle:#"Alert Title"
message:#"are you sure?"
delegate:self
cancelButtonTitle:#"No"
otherButtonTitles:#"Yes", nil];
return YES;
}
[UIAlertController alertControllerWithTitle:#"Pin" message:#"Fail" preferredStyle:UIAlertControllerStyleAlert];
return NO;}
I have tried both the UIAlertView and UIAlertController method but I get no response to the app. Can someone correct this code in ObjC?
Thanks
There's no need to create method, you can directly check and shoe an alert like this.
- (IBAction)validatePin:(id)sender {
if (self.textPin.text.integerValue == 1408) {
UIAlertController* alert = [UIAlertController alertControllerWithTitle:#"Alert Title"
message:#"PIN is Correct"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
}
else {
UIAlertController* alert = [UIAlertController alertControllerWithTitle:#"Alert Title"
message:#"PIN is WRONG"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
}
}
If you want to use your code then change it to this.
- (IBAction)validatePin:(id)sender {
BOOL isValidPin = [ViewController checkPin:self.textPin.text.integerValue];
if (isValidPin) {
// SHOW RIGHT ALERT
}
else {
// SHOW WRONG ALERT
}
}
+(BOOL)checkPin:(NSInteger)pin {
if (pin == 1408) {
return YES;
}
else {
return NO;
}
}
I am trying to fix on iOS 7+ an alert allowing me to input a 4 digit code, at the moment, the prompt appears, but the input field is blank and does not allow me to put anything in.
The methods below are used to call the pin code option, starting with the segmentedAction as seen below;
-(void)segmentedAction:(id)sender{
UISegmentedControl *control = (UISegmentedControl *)sender;
NSString *pincode = [self.objSettingAdapter getPinCode];
NSString *patternCode = [self.objSettingAdapter getPatternCode];
NSInteger pincodetype = control.selectedSegmentIndex;
if ((![pincode length]>0) && pincodetype==0) {
[self takePinInputFromUser:#"Choose Your PIN Code"];
}else if((![patternCode length]>0) && pincodetype==1) {
[self takePatterInputFromUser:#"Draw Pattern"];
}else {
[self.objSettingAdapter setPinCodeType:control.selectedSegmentIndex];
}
}
-(void)buttonAction:(id)sender{
UIButton *btn = (UIButton *)sender;
NSString *pincode = [self.objSettingAdapter getPinCode];
NSString *patternCode = [self.objSettingAdapter getPatternCode];
if ([btn.titleLabel.text isEqualToString:#"Reset PIN"] && (![pincode length]>0)) {
[self takePinInputFromUser:#"Choose Your PIN Code"];
}else if ([btn.titleLabel.text isEqualToString:#"Reset Pattern"] && (![patternCode length]>0)) {
[self takePatterInputFromUser:#"Draw Pattern"];
}else {
[self.objSettingAdapter setPinCodeType:([btn.titleLabel.text isEqualToString:#"Reset PIN"] ? 0 : 1)];
}
}
-(void)takePinInputFromUser:(NSString *)title{
AlertPinCode *prompt = [AlertPinCode alloc];
prompt = [prompt initWithTitle:title message:#"\n\n" delegate:self cancelButtonTitle:#"Cancel" okButtonTitle:#"Done"];
[prompt show];
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
AlertPinCode *alertPin = (AlertPinCode *) alertView;
if (buttonIndex != [alertView cancelButtonIndex])
{
NSString *userPin = [alertPin enteredText];
if ([userPin length]<4) {
[alertPin dismissWithClickedButtonIndex:0 animated:YES];
[self takePinInputFromUser:#"Chose 4 Digit PIN Code"];
}else {
[self.objSettingAdapter setPinCodeType:0];
[self.objSettingAdapter setPinCode:userPin];
}
}
}
Try the following.
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Title" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleCancel handler:nil];
__weak typeof(UIAlertController) *weakAlertController = alertController;
UIAlertAction *okAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
__strong typeof(UIAlertController) *strongAlertController = weakAlertController;
UITextField *digitTextField = [strongAlertController.textFields firstObject];
NSString *pinCode = digitTextField.text;
NSLog(#"pin code: %#", pinCode);
// Do something with the PIN code
}];
[alertController addAction:cancelAction];
[alertController addAction:okAction];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.placeholder = #"Input 4 Digit PIN Code";
}];
[self presentViewController:alertController animated:YES completion:nil];
you can use UIAlertViewController
Can anyone advise as I have an email field in an alert with submit and cancel buttons.
I have a Bool function which returns the email validation result which I'm using in UIAlertAction and showing a custom message with NSLog statement.
My question is when user presses submit button and if bool value is zero, I want to show the entered email text in the UITextField along with an error message in red at the bottom of the text field. Also alert should be visible until the bool value is returned as 1.
Code:
UIAlertController * alert= [UIAlertController
alertControllerWithTitle:#"Forgot Password"
message:#"" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* submit = [UIAlertAction
actionWithTitle:#"Submit"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
//Do Some action here
UITextField *alertTextField = alert.textFields.firstObject;
NSLog(#"%d",[self validateEmailWithString:alertTextField.text]);
int returnValue = (int)[self validateEmailWithString:alertTextField.text];
NSLog(#"interger value %i",returnValue);
if ( returnValue == 1) {
NSLog(#"correct format");
}else
NSLog(#"wrong format");
}];
UIAlertAction* cancel = [UIAlertAction
actionWithTitle:#"Cancel"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:submit];
[alert addAction:cancel];
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = #"Enter your E-Mail Address";
_enteredEMail = textField.text;
NSLog(#"%#ntered Email Address",textField.text);
UIAlertController does not support an error message in red at the bottom of the text field but you can change colour of text field.
Add this method to check length of textField.text or you can add email validation check and then enable submit button.
submit.enabled = NO; //after submit button UIAlertAction set
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *finalString = [textField.text stringByReplacingCharactersInRange:range withString:string];
[submit setEnabled:(finalString.length >= 1)];
// for textField border colour
textField.layer.borderColor=[[UIColor redColor]CGColor];
textField.layer.borderWidth= 2.0f;
return YES;
}
You can't hold the dialog box but to can call it again from submit button action if returnValue == 0.
if ( returnValue == 0) {
NSLog(#"correct format");
}
else{
NSLog(#"wrong format");
[self presentViewController:alert animated:YES completion:nil];
}
Also refer UIAlertView Text Input and Validation.
I'm trying to make a login dialog in UIAlertController.
Here is my code:
+ (void)authorizationDialogShow
{
__block UITextField *loginTextField;
__block UITextField *passwordTextField;
UIAlertController *authorizationAlert = [UIAlertController alertControllerWithTitle:#"Authorization"
message:#"Enter login and password."
preferredStyle:UIAlertControllerStyleAlert];
[authorizationAlert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
loginTextField = textField;
loginTextField.placeholder = #"Login";
}];
[authorizationAlert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
passwordTextField = textField;
passwordTextField.placeholder = #"Password";
passwordTextField.secureTextEntry = YES;
}];
[authorizationAlert addAction:[UIAlertAction actionWithTitle:#"Login"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * _Nonnull action) {
NSString *login = loginTextField.text;
NSString *password = passwordTextField.text;
[GitAuthorization startAuthorizationWithLogin:login password:password];
}]];
[authorizationAlert addAction:[UIAlertAction actionWithTitle:#"Cancel"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction * _Nonnull action) {
NSLog(#"End editing");
[authorizationAlert.view endEditing:YES];
[loginTextField resignFirstResponder];
[passwordTextField resignFirstResponder];
}]];
[authorizationAlert show];
}
The problem is in cancel UIAlertAction. When I pressed this action, the keyboard dismissed with some delay. Not at the same time as UIAlertController. What's the problem?
I'm using pod FFGlobalAlertController. Here some example of this.
I have the same issue using UIAlertController.
My solution is to add a category on UIAlertController and call [self.view endEditing:YES] on viewWillDisappear. Import the category in prefix.pch if it's used widely.
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[self.view endEditing:YES];
}
Thank for the answer from micap. See link below for detail:
iOS 8 Keyboard Dismissed delay after modal view controller is dismissed
I'm using UIAlertController for the first time. I need to prompt the user for an input. Anyway, the following is what I have.
- (void)showAlert {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Hello!" message:#"Type something.") preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *noButton = [UIAlertAction actionWithTitle:#"Cancel") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
}];
UIAlertAction *yesButton = [UIAlertAction actionWithTitle:#"Enter") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//NSString *input = alert.textFields[0].text;
//NSLog(#"input was '%#'", input);
UITextField *textField = alert.textFields[0];
NSLog(#"%#",textField.text); // <====== It's not returned
}];
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
[textField addTarget:self action:#selector(alertTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
[yesButton setEnabled:NO];
}];
[alert addAction:noButton];
[alert addAction:yesButton];
[self presentViewController:alert animated:YES completion:nil];
}
- (void)alertTextFieldDidChange:(UITextField *)sender {
UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
if (alertController) {
UITextField *textfield = alertController.textFields.firstObject;
UIAlertAction *okAction = alertController.actions.lastObject;
okAction.enabled = [self validateName2:textfield.text:5]; // function for validating user input
}
}
For some reason, when the user tap Yes, the application doesn't return user input. In fact, Xcode dashes 'text' as in 'NSString *input = alert.textFields[0].text. A strange thing is that UIAlertView doesn't return user input. That's why I've switched to UIAlertController.
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
if ([alertView tag] == 101) {
if (buttonIndex == 1) {
NSString *username = [[alertView textFieldAtIndex:0] text];
NSLog(#"%#",username); // <====== It's never returned.
}
}
}
Anyway, I wonder what I'm doing wrong with UIAlertController?
Muchos thankos
p.s. I'm using Xcode 6.4 (6E35b). This issue may be caused by Xcode. If I debug the code with the iPad2 simulator, it'll actually return user input while it doesn't if I use the iPhone4S simulator.
Use this for textField in alertcontroller
__block typeof(self) weakSelf = self;
UIAlertController *alertController;
alertController = [UIAlertController alertControllerWithTitle:title
message:message
preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField)
{
textField.tag = 1001;
textField.delegate = weakSelf;
textField.placeholder = #"";
[textField addTarget:weakSelf action:#selector(alertTextFieldDidChange:)
forControlEvents:UIControlEventEditingChanged];
}];
//OK Button
UIAlertAction *okAction = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action)
{
UITextField *textField = alertController.textFields.firstObject;
// Do stuff here
}];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
- (void)alertTextFieldDidChange:(UITextField *)sender
{
alertController = (UIAlertController *)self.presentedViewController;
if (alertController)
{
UITextField *textField = alertController.textFields.firstObject;
UIAlertAction *okAction = alertController.actions.lastObject;
okAction.enabled = textField.text.length > 0; // condition to enable button
}
}
#pragma mark - UITextField delegate methods
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
I would recommend using UITextFieldDelegate to handle the textField!
Set textField.delegate = self and then use the - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string method to do what you do in alertTextFieldDidChange if the replacementString has a length of > 0.
You are provided with delegate methods for UITextField so you don't have to create the selectors yourself, I recommend you use them to their fullest!
Here are the docs in case you want to know more! https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextFieldDelegate_Protocol/