how to do validation for username in [objective-c]? - ios

my requirement for validation is to validate username which allows to enter small a-z,and 0-9, and only two symbol _ and .(dot)
but symbol do not repeat.
and symbol not allowed at the starting of the name.
can any one help me ?? how to do this validation?
i have tried this code but it works fine but it repeats symbol how can i avoid to repeat?
- (BOOL)validateString:(NSString*)stringToSearch
{
NSString *emailRegex = #"[a-z0-9._]{5,15}";
NSPredicate *regex = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
return [regex evaluateWithObject:stringToSearch];
}

Use the following regex to check if the characters are correct:
^([a-z0-9]+[._])*[a-z0-9]+$
Debuggex Demo
Additionally and separately check the string length. (or use lookaheads)
Edit: it seems like I misread some of the requirements. The above regex disallows symbol at the end of the name as well. If you want to allow symbols there, change the regex to
^([a-z0-9]+[._]?)*$
If you use predicates you can omit the leading ^ and trailing $.

Pure regex approach, used lookahead for count, might have other simplified solution
"(?=[a-z0-9._]{5,15})([a-z0-9][._]?)+"
EDIT
Regarding the additional question: What to avoid the user enter rejected characters
Technically you can achieve that by implementing the UITextViewDelegate method textView(_:shouldChangeTextInRange:replacementText:). But it might give the user impression that the keyboard is not responding correctly.
So it might be a better user experience that implementing textViewShouldEndEditing(_:) method with some kind of alert showing the alert.

define Validation #"abcdefghijklmnopqrstuvwxyz0123456789_."
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *unacceptedInput = nil;
unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:ALPHA] invertedSet];
if ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] <= 1) {
int newLength = (int)textField.text.length + (int)string.length - (int)range.length;
if (newLength > 50) {
return false;
} else {
return true;
}
} else {
return false;
}
}
here I had to also put validation for text length not exceed 50 characters in my project so you can remove that condition

Related

Can one define NSFound macro?

This may sound like a silly question but Apple provides us with NSNotFound but why didn't they provide one called NSFound? Is there a way one can define a NSFound macro on their own?
The reason I am asking all this is that in order for me to check if a string "contains" a certain character I have to do double negative i.e.
if ([XML rangeOfString:#"error" options:NSCaseInsensitiveSearch].location != NSNotFound)
{
//server is down
}
else
{
//server is up
}
At least for me this would have been so much easier to read if I could simply do this instead
if ([XML rangeOfString:#"error" options:NSCaseInsensitiveSearch].location == NSFound)
{
//server is down
}
else
{
//server is up
}
If I want to define NSFound or SAMFound, how would I go about doing that?
Your issue is really with the design pattern methods like rangeOfString follow - using a single return value for both valid results, of which there are many, and failure indications, of which there is one. You can test for a single failure value with a comparison to a constant, NSNotFound in this case, but you cannot likewise test for many possible values with a simple comparison - instead you use the "double negative" you don't like.
If you find it too ugly change it... Maybe:
#interface NSString (SamExtras)
- (BOOL) SAMcontainsString:(NSString *)string options:(NSStringCompareOptions)options;
#end
#implementation NSString (SamExtras)
- (BOOL) SAMcontainsString:(NSString *)string options:(NSStringCompareOptions)options
{
return [self rangeOfString:string options:options].location != NSNotFound;
}
#end
Which would allow you to use:
if ([XML SAMcontainsString:#"error" options:NSCaseInsensitiveSearch])
{
//server is down
}
else
{
//server is up
}
with no double negative. You can write the category once and use it in all your projects.
HTH
Double Negative doesn't have the consequences in code as it does in grammar.
The reason they provide a not found, as opposed to a found version, is simply the not found value is a single (supposedly invalid) value and everything else is valid. It's therefore simpler to define this single, invalid value.
Also it makes more sense (more efficient, avoiding a double-search and less code) to store the NSRange in a local variable in order to firstly test for validity and then to use the value:
NSRange range = [XML rangeOfString:#"error" options:NSCaseInsensitiveSearch];
if (range.location != NSNotFound) {
// Do thing with range
} else {
// Complain
}
There is nothing whatever wrong with your original test:
if ([XML rangeOfString:#"error" options:NSCaseInsensitiveSearch].location != NSNotFound) {
If all you need to know is whether XML contains the string #"error", that test answers the question and is a perfectly legitimate and idiomatic way to ask it. Observe that even the documentation tells you that containsString: is nothing but a front for calling rangeOfString:options:!
If you really want to know what the positive version would be, it would be to test the length of the returned range and see if it is the same as the length of #"error". The length of a not-found range is 0.

Validate string with various validation in iOS

I've been facing some issue with to valid string with following condition. The respective conditions are as follows:
String should contain MAX length(which is 7) and should not less Than 6
First character must be from A-Z (should consider aUppercase only)
remaining character must contain only digit (0 to 9).
Here is an example of String I want to valid A12342 (desire output with validation)
Thanks in advance ,Any help will be appreciated.If any one need more information about my query please let me know .
-(BOOL)CheckConditionForValidation
{ if([textfield.text isequalToString:#""]){
return FALSE
}
//else if (//validation for my specific number)
//{
//want to implement logic here
//}
}
Try this rejex pattern [A-Z][0-9]{5,6}
check it online with the link Online rejex check
and if it work than use like this
- (BOOL)checkValidation:(UITextField *)textField
{
NSString *rejex = #"<your pattern>";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", rejex];
//if rejex fullfil than it will return true else false.
return [emailTest evaluateWithObject:textField.text];
}

NSDecimalNumber notANumber is not true for letter 'E'

Im trying to apply validation on UITextField in such a way that it should not accept anything rather than decimal number.
I used following delegate method of UITextField:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSDecimalNumber *number2 = [NSDecimalNumber decimalNumberWithString:string];
if (!string || [string length] < 1 || [string isEqualToString:#""] )
{
return YES;
}
if (!number2 || [number2 isEqualToNumber:[NSDecimalNumber notANumber]])
{
return NO;
}
return YES;
}
Its working perfect,but it has two issues.
1. when i'm entering value 'E' or 'e' its accepting it.
2.Once it accepted letter 'E' or 'e',Its accepting all other english letters.
This is from the documentation.
Besides digits, numericString can
include an initial “+” or “–”; a single “E” or “e”, to indicate the
exponent of a number in scientific notation; and a single
NSLocaleDecimalSeparator to divide the fractional from the integral
part of the number.
Maybe you can use NSRegularExpression instead
You should use NSNumberFormatter to validate numeric user input.

Limiting user input in a UITextField to a certain range of numbers (not number of characters)

I would like to limit user input in a UITextField to 1-105. I have set the delegate and have successfully limited the actual number of characters via the following code, found elsewhere on Stackoverflow. Is there something that I can add in order to force the user to input any integer between 1 and 105?
#define MAXLENGTH 2
- (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger oldLength = [_startLevel.text length];
NSUInteger replacementLength = [string length];
NSUInteger rangeLength = range.length;
NSUInteger newLength = oldLength - rangeLength + replacementLength;
BOOL returnKey = [string rangeOfString: #"\n"].location != NSNotFound;
return newLength <= MAXLENGTH || returnKey;
}
I am using the number keypad, so the user is already limited to entering numbers. I just need to find something that will make them input something in the range.
Thanks in advance.
First convert the string to a number. In order of ease of use and lack of control, the ways you do that are -[NSString integerValue]*, NSNumberFormatter, and NSScanner. The formatter will give you an NSNumber from which you can then get the integerValue*; the other two get you primitives directly.
Once you have that, compare the number to the endpoints of your range, creating a boolean. Combine that boolean with the other two -- for length and lack of newline -- you already have, and return the result.
*For floating point, either floatValue or doubleValue.
In didEndEditing, get the text, convert it to an integer, and check the value. If it's out of range, display an error message. You might also reset the text to it's previous value, assuming it starts out in-range.
I've used a regular expression to validate inputs to the right format. I found some documentation on line on RegEx that I was able to use to build my expression. You might create a regular expression that requires the input to be 1, 2, or 3 digits. I'm no expert, but the string #"^[0-9]{1,3}$" should require 1 to 3 digits between 0 and 9 (the 0-9 defines the legal characters, and the {1,3} means that the user can enter 1 through 3 of them. The ^ at the beginning anchors the expression to the beginning of the string, and the "$" at the end anchors the expression to the end of the string.)
You can use the code below
NSString *numberRegex = #"[1-9]||[0-9][1-9]||[0-1]0[0-5]";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", numberRegex];
BOOL b = [emailTest evaluateWithObject:numberField.text];
if (b)
{
//Code when number is in the range 1-105
}
else
{
//Code when number is not in the range 1-105
}
Hope this helps you

How to validate fractional number

I am trying to write a function that returns boolean value if given string is in valid fractional format or not.
e. g. fraction numbers are as follows
2/3,
1 2/3,
6/5,
80/20,
60 1/4,
etc.
-(BOOL)validateFraction:(NSString *)string
{
if(string is valid fraction)
return YES;
else
return NO;
}
You can use regular expressions for that:
-(BOOL)validateFraction:(NSString *)string{
NSString *fractionRegex = #"\\d+(/\\d+)?";
NSPredicate *fractionTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", fractionRegex];
return [fractionTest evaluateWithObject:string];
}
P.S. not also, that that function does not validate against division by zero and does not allow fraction to have sign (+ or -) at front
I found a solution which accepts numbers such as 1/210 2/35 6/8etc.
-(BOOL)validateFraction:(NSString *)string{
NSString *fractionRegex = #"[1-9]?[ ]?[0-9]+/[1-9]+";
NSPredicate *fractionTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", fractionRegex];
return [fractionTest evaluateWithObject:string];
}
You can do something like this:
-(BOOL)validateFraction:(NSString *)string
{
if ([string rangeOfString:#"/"].location == NSNotFound) {
return NO;
}
return YES;
}
This code will only see if the string #"/" appears as substring in the given string.
As you can see, this is a very simple solution, and may work if you know that the strings that you want to test are all numerical valid ones. If you want something more robust, that tests for "invalid" strings, just use regular expressions, like in #Vladimir's answer

Resources