Validations in UITextField - uitextfield

I have 3 UITextFields(name, email, phoneNumber). I want to put validations which are:
Name -> Allowed: (a-z), (A-Z)
Email -> Allowed: ensure it ends with something like this "#gmail.com"
PhoneNumber -> Allowed: (0-9), and has 10 digits.
Also, for number field, the keypad should be numeric keypad.

For email validation:-
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+#gmail+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %#", emailRegEx)
return emailTest.evaluate(with: testStr)
}
How to use:-
if isValidEmail(testStr: "john#gmail.com"){
print("Valid emailID")
}
else{
print("invalide EmailID")
}

Related

How can I filter() stream method using regexp and predicate to get negated list

I am trying to filter anything not in the regexp.
So what I am trying to express is write anything to a list that has characters other than a-z,0-9 and -, so I can deal with these city names with invalid characters afterwards.
But whatever I try I either end up with a list of valid cities or an IllegalArgumentException where the list contains valid character cities.
String str;
List<String> invalidCharactersList = cityName.stream()
.filter(Pattern.compile("[^a-z0-9-]*$").asPredicate())
.collect(toList());
// Check for invalid names
if (!invalidCharactersList.isEmpty()) {
str = (inOut) ? "c" : "q";
throw new IllegalArgumentException("City name characters "
+ str + ": for city name " + invalidCharactersList.get(0)
+ ": fails constraint city names [a-z, 0-9, -]");
}
I am try to filter anything not in the regexp
Following is some test data which fails on the first list, I want it to fail on last
List<String> c = new ArrayList<>(Arrays.asList("fastcity", "bigbanana", "xyz"));
List<Integer> x = new ArrayList<>(Arrays.asList(23, 23, 23));
List<Integer> y = new ArrayList<>(Arrays.asList(1, 10, 20));
List<String> q = new ArrayList<>(Arrays.asList("fastcity*", "bigbanana", "xyz&"));
Following is output:
#Holger
filter(Pattern.compile("[^a-z0-9-]").asPredicate())
Thanks this works fine.

Google Sheets API adding single qoute to text

Hi I am running a Google APi script to enter data into a sheet but for some text (number,dates, booleans) it's adding a ' before e.g 05/01/2021 = '05/01/2021
I am using batch update:
def turn_into_range(data, SheetId, row,cols):
rows = [{'values': [{'userEnteredValue': {'stringValue': f}} for f in e]} for e in data]
rng = {'sheetId': SheetId, 'startRowIndex': 0, 'startColumnIndex': 0}
fields = 'userEnteredValue'
body = {'requests': [{'updateCells': {'rows': rows, 'range': rng, 'fields': fields}},{
"updateSheetProperties": {
"properties": {
"gridProperties": {
"rowCount": row + 1,
"columnCount": cols
},
"sheetId": SheetId
},
"fields": "gridProperties"
},
}
]}
clean_dict = simplejson.loads(simplejson.dumps(body, ignore_nan=True))
return clean_dict
def post_sheet(service_sheets, spreadsheet_id, body):
request = service_sheets.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id, body=body)
response = request.execute()
return response
any ideas?
For this issue, it is because your data is treated as string in stringValue.
You need to use other types of values for different data types,
stringValue:
"A String", # Represents a string value.
Leading single quotes are not included. For example, if the user typed '123 into the UI, this would be represented as a stringValue of "123".
boolValue:
True or False, # Represents a boolean value.
numberValue:
3.14, # Represents a double value.
Note: Dates, Times and DateTimes are represented as doubles in "serial number" format.
formulaValue:
"A String", # Represents a formula.
errorValue:
An error in a cell. Represents an error.
This field is read-only.
Try adding this in your code.
from dateutil.parser import parse
def checkData(data):
if (isinstance(data, bool)):
return 'boolValue'
try:
if (isinstance(data, (int, float)) or parse(data)):
return 'numberValue'
except ValueError:
return 'stringValue'
Behaviour:
Now, use it in your code:
rows = [{'values': [{'userEnteredValue': {checkData(f): f}} for f in e]} for e in data]
For more details, documentation can be found here

LINQ: select rows where any word of string start with a certain character

I want extract from a table all rows where in a column (string) there is at least one word that starts with a specified character.
Example:
Row 1: 'this is the first row'
Row 2: 'this is th second row'
Row 3: 'this is the third row'
If the specified character is T -> I would extract all 3 rows
If the specified character is S -> I would extract only the second column
...
Please help me
Assuming you mean "space delimited sequence of characters, or begin to space or space to end" by "word", then you can split on the delimiter and test them for matches:
var src = new[] {
"this is the first row",
"this is th second row",
"this is the third row"
};
var findChar = 'S';
var lowerFindChar = findChar.ToLower();
var matches = src.Where(s => s.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Any(w => w.ToLower()[0] == lowerFindChar));
The LINQ Enumerable.Any method tests a sequence to see if any element matches, so you can split each string into a sequence of words and see if any word begins with the desired letter, compensating for case.
Try this:
rows.Where(r => Regex.IsMatch(r, " [Tt]"))
You can replace the Tt with Ss (both assuming you want either upper case or lower case).
The problem of course is, what is a "word"?
Is the character sequence 'word' in the sentence above a word according to your definition? It doesn't start with a space, not even a white-space.
A definition of a word could be:
Define wordCharacter: something like A-Z, a-z.
Define word:
- the non-empty sequence of wordCharacters at the beginning of a string followed by a non-wordcharacter
- or the non-empty sequence of wordCharacters at the end of a string preceded by a non-wordcharacter
- any non-empty sequence of wordCharacters in the string preceded and followed by a non-wordcharacter
Define start of word: the first character of a word.
String: "Some strange characters: 'A', 9, äll, B9 C$ X?
- Words: Some, strange characters, A
- Not Words: 9, äll, B9, C$ X?
So you first have to specify precisely what you mean by word, then you can define functions.
I'll write it as an extension method of IEnumerable<string>. Usage will look similar to LINQ. See Extension Methods Demystified
bool IsWordCharacter(char c) {... TODO: implement your definition of word character}
static IEnumerable<string> SplitIntoWords(this string text)
{
// TODO: exception if text null
if (text.Length == 0) return
int startIndex = 0;
while (startIndex != text.Length)
{ // not at end of string. Find the beginning of the next word:
while (startIndex < text.Length && !IsWordCharacter(text[startIndex]))
{
++startIndex;
}
// now startIndex points to the first character of the next word
// or to the end of the text
if (startIndex != text.Length)
{ // found the beginning of a word.
// the first character after the word is either the first non-word character,
// or the end of the string
int indexAfterWord = startWordIndex + 1;
while (indexAfterWord < text.Length && IsWordCharacter(text[indexAfterWord]))
{
++indexAfterWord;
}
// all characters from startIndex to indexAfterWord-1 are word characters
// so all characters between startIndexWord and indexAfterWord-1 are a word
int wordLength = indexAfterWord - startIndexWord;
yield return text.SubString(startIndexWord, wordLength);
}
}
}
Now that you've got a procedure to split any string into your definition of words, your query will be simple:
IEnumerabl<string> texts = ...
char specifiedChar = 'T';
// keep only those texts that have at least one word that starts with specifiedChar:
var textsWithWordThatStartsWithSpecifiedChar = texts
// split the text into words
// keep only the words that start with specifiedChar
// if there is such a word: keep the text
.Where(text => text.SplitIntoWords()
.Where(word => word.Length > 0 && word[0] == specifiedChar)
.Any());
var yourChar = "s";
var texts = new List<string> {
"this is the first row",
"this is th second row",
"this is the third row"
};
var result = texts.Where(p => p.StartsWith(yourChar) || p.Contains(" " + yourChar));
EDITED:
Alternative way (I'm not sure it works in linq query)
var result = texts.Where(p => (" " + p).Contains(" " + yourChar));
you can use .ToLower() if you want Case-insensitive check.

How do I match only some, not all variants of an enum?

I've looked everywhere and cannot find a clear cut example. I want to be able to only match some, not all variants of an enum.
pub enum InfixToken {
Operator(Operator),
Operand(isize),
LeftParen,
RightParen,
}
So I can perform this in a for loop of tokens:
let x = match token {
&InfixToken::Operand(c) => InfixToken::Operand(c),
&InfixToken::LeftParen => InfixToken::LeftParen,
};
if tokens[count - 1] == x {
return None;
}
How do I compare if the preceding token matches the only two variants of an enum without comparing it to every variant of the enum? x also has to be the same type of the preceding token.
Also, and probably more important, how can I match an operand where isize value doesn't matter, just as long as it is an operand?
You can use _ in patterns to discard a value: InfixToken::Operand(_) => branch. If the whole pattern is _, it will match anything.
To only perform code if specific variants are matched, put that code in the match branch for those variants:
match token {
&InfixToken::Operand(_) |
&InfixToken::LeftParen => {
if tokens[count - 1] == token {
return None;
}
}
_ => {}
}
The bar (|) is syntax for taking that branch if either pattern is satisfied.
In cases where you only want to match one variant of an enum, use if let

How to get nsstring matching count with other nsstring object?

I searching a way to get match count of nsstring objects for a long time.
but I can't find.
How to get match count of String_one and String_Two?
I need your help..
NSString *String_one = #"A!B!C!D!E!F!G";
NSString *String_Two = #"BEF";
// matching progress
// :
// :
// and then result display
NSLog(#"matching count : %d",[??????]);
// result what i want.
// matching count : 3 (A!B!C!D!E!F!G vs BEF => 3 character matches)
If you want to find longest common subsequence here you have link:
http://en.wikipedia.org/wiki/Longest_common_subsequence_problem
But if you want count only how many how many character from first string appear in second string you can write algorithm by yourself. Example:
for ( each character in StringFirst ) {
if( character appear in StringSecond )
++count;
}

Resources