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];
}
Related
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.
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
Does anyone now how I can check if a text field NEARLY matches a set text?
I know how to check if it exactly matches, but i want it to know if its even close to the set text
So if they type HELLO WORD it indicates its close but not exact match?
if (([textfield.text isEqual:#"HELLO WORLD"]))
{
NSLog(#"Correct");
} else {
NSLog(#"Incorrect");
}
This library may be of use to you. And since it's open source, you can check the source to see how it's done. :)
Use this
For Case Insensitive :
if( [textfield.text caseInsensitiveCompare:#"My Case sensitiVE"] == NSOrderedSame ) {
// strings are equal except for possibly case
}
For Case Sensitive :
if([textfield.text isEqualToString:#"My Case sensitiVE"]) {
// Case sensitive Compare
}
You can compare each index of two string and see how many difference is there. And you should define your "nearly match", it may be difference in single character or in multiple character. And decide if you should accept it or reject it.
If you like algorithm Longest Common Subsequence is a key to your goal.. :)
use
NSString caseInsensitiveCompare:
or
- (NSComparisonResult)compare:(NSString *)aString
options:(NSStringCompareOptions)mask`
NSString *string = #"HELLO WORLD I AM JACK";
if ([string rangeOfString:#"HELLO WORLD"].location == NSNotFound) {
NSLog(#"string does not contain HELLO WORLD");
} else {
NSLog(#"string contains HELLO WORLD!");
}
I am currently trying to check the length of a label.
What it is is i want the label to display "Unavailable" if the string is of a null value.
The sting is being read in from a XML sheet so i don't know what the length of the actual string is and i would like to know. This is what i currently have but its not working.
It displays the relevant text if its not empty which is brilliant.
But its not displaying the text when it is empty which is leading me to believe although i assume its empty its not.
Thanks in advance.
if ([l_subCommunity.text length] > 0)
{
[l_subCommunity setText:_property.str_subCommunity];
NSLog(#"%",l_subCommunity);
}
else
{
NSMutableString *sub = [[NSMutableString alloc]init];
[sub appendString:#"Unavailable"];
[self.l_subCommunity setText:sub];
}
[l_subCommunity setText:_property.str_subCommunity];
[self.l_subCommunity setText:sub];
you are using l_subCommunity setText in the if and self.l_subCommunity setText in the else. are you using 2 different variables?
Also why are you creating a mutable string to pass in the value #"Unavailable" ?
why not simply:
[self.l_subCommunity setText: #"Unavailable" ];
Your if statement is checking the wrong variable. You want:
if (_property.str_subCommunity.length) {
l_subCommunity.text = _property.str_subCommunity;
NSLog(#"%",l_subCommunity);
} else {
self.l_subCommunity.text = #"Unavailable";
}
Also keep in mind that you may end up with whitespace and/or newlines in your string as a result of parsing the XML file. You may need to trim this whitespace from your string.
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