简体   繁体   中英

how to validate textfield that allows . only once with in the textfield

I have 4 text fields in my application.

I validate my textfields as textfield allow 0,1,...9 and . ,for that i write code as fallows

- (IBAction) textfield:(id)sender {

    if ([textfield.text length] > 0) {
        if ([textfield.text length] > 10){          
            textfield.text = [textfield.text substringWithRange:NSMakeRange(0, 10)];
    }
        else {
            //retrieve last character input from texfield           
            int I01 = [homevalue.text length];
            int Char01 = [homevalue.text characterAtIndex:I01-1];
            //check and accept input if last character is a number from 0 to 9
            if ( (Char01 < 46) || (Char01 > 57) || (Char01 == 47) ) {

                if (I01 == 1) {
                    textfield.text = nil;
                }
                else {

                    textfield.text = [homevalue.text substringWithRange:NSMakeRange(0, I01-1)];
                }
            }

        }
    }

} 

It works fine, Now i need to validate that . allows only once with in the textfield.

eg: 123.45

According to my code if i place again . it is allowed. eg:123.45.678

But it wont allowed once i place . ,that textfield wont allowed.

ed:123.45678.

How can i done this,

can any one pls help me.

Thank u in advance.

Try this predicate for texts that start with a number like "23.67"

NSString *decimalRegex = @"[0-9]+([.]([0-9]+)?)?"; // @"[0-9]+[.][0-9]+";
NSPredicate *decimalTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", decimalRegex]; 
BOOL isValidDecimal = [decimalTest evaluateWithObject:[textField text]];

If you want to allow "." at the fist place like ".95" use the following regex,

NSString *decimalRegex = @"[0-9]*([.]([0-9]+)?)?"; //@"[0-9]*[.][0-9]+";

Your code should look like this,

- (IBAction)textfield:(id)sender {

    int textLength = [[textfield text] length];

    if (textLength > 0) {

        NSString *decimalRegex = @"[0-9]+([.]([0-9]+)?)?"; //@"[0-9]+[.][0-9]+";
        NSPredicate *decimalTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", decimalRegex]; 
        BOOL isValidDecimal = [decimalTest evaluateWithObject:[textField text]];

        if (!isValidDecimal) {

            NSString *text = [[textField text] substringToIndex:textLength - 1];
            [textfield setText:text] 
        }
    } 
}

I guess this should work! Give it a try!

Well you can use this method

- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet options:(NSStringCompareOptions)mask range:(NSRange)aRange

on textfield.text as its a NSString only

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM