简体   繁体   中英

How to avoid unwanted characters in UITextfield?

In my textfield it should allow both positive and negative decimal values. So I used the regex

#define FLOAT_REGEX @"-[0-9]+(\.[0-9][0-9]?)?"

-(BOOL) checkForDecimalValue:(NSString *) string
{
NSPredicate *confidenceTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",FLOAT_REGEX]; 
return [confidenceTest evaluateWithObject:string]?YES:NO;
}

But it is not accepted if I enter only positive values without any decimal point (for ex 100,200, etc). It should allow positive values and integer also.

replace the line use the following:

#define FLOAT_REGEX @"^[-]?[0-9]*(.[0-9]*)?$"

Hope this helps in what you want. Check its validity from here

A digit in the range 1-9 followed by zero or more other digits:

^[1-9]\d*$

To allow numbers with an optional decimal point followed by digits. A digit in the range 1-9 followed by zero or more other digits then optionally followed by a decimal point followed by at least 1 digit:

^[1-9]\d*(\.\d+)?$

Notes:

The ^ and $ anchor to the start and end basically saying that the whole string must match the pattern

()? matches 0 or 1 of the whole thing between the brackets

Update to handle commas:

In regular expressions . has a special meaning - match any single character. To match literally a . in a string you need to escape the . using \\. This is the meaning of the \\. in the regexp above. So if you want to use comma instead the pattern is simply:

^[1-9]\d*(,\d+)?$

Further update to handle commas and full stops

If you want to allow a . between groups of digits and a , between the integral and the fractional parts then try:

^[1-9]\d{0,2}(\.\d{3})*(,\d+)?$

ie this is a digit in the range 1-9 followed by up to 2 other digits then zero or more groups of a full stop followed by 3 digits then optionally your comma and digits as before.

If you want to allow a . anywhere between the digits then try:

^[1-9][\.\d]*(,\d+)?$

ie a digit 1-9 followed by zero or more digits or full stops optionally followed by a comma and one or more digits.

ref : Decimal or numeric values in regular expression validation

hope it helps, happy coding :)

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