Driver's License Verification in Flutter / Dart - dart

Does anyone know of an API or package that can be used in a flutter project that would allow me to check whether a driver's license number is valid or not? I'm working with US driver's licenses if that makes a difference.

Seems like there's no plugin for that yet, but since it can be done fairly the same way in most languages, it's been done already. Take a look: https://stackoverflow.com/a/29835561/6696558.
In Dart it would something like this:
class DriverLicenseValidator {
// From http://www.uiia.org/documents/license_guidelines_08.pdf
static final oneToSevenNumeric = RegExp(r'^[0-9]{1,7}$');
static final oneAlpha = RegExp(r'(.*[A-Za-z]){1}');
static final oneAlphaPlusSeven = RegExp(r'^.[0-9]{7}$');
static final twoAlpha = RegExp(r'(.*[A-Za-z]){2}');
static final alphaPlusSixNumeric = RegExp(r'(.*[0-9]){6}$');
static final threeToFiveNumeric = RegExp(r'(.*[0-9]){3,5}$');
static final fiveToNineNumeric = RegExp(r'(.*[0-9]){5,9}');
static final sixNumeric = RegExp(r'^[0-9]{6}$');
static final sevenNumeric = RegExp(r'^[0-9]{7}$');
static final sevenToNineNumeric = RegExp(r'^[0-9]{7,9}$');
static final eightAreNumbers = RegExp(r'(.*[0-9]){8}');
static final nineNumeric = RegExp(r'^[0-9]{9}$');
static final nineAlphaChars = RegExp(r'^[A-Za-z0-9]{9}$');
static final tenNumeric = RegExp(r'^[0-9]{10}$');
static final elevenNumeric = RegExp(r'^.[0-9]{11}$');
static final twelveNumeric = RegExp(r'^.[0-9]{12}$');
static final hPlusEight = RegExp(r'([H][0-9]{8})$');
static final sevenPlusX = RegExp(r'([H][0-9]{7}X)$');
/// If there's no error, returns an empty [String]
/// If there's an error, returns an error [String]
static String checkForError(String stateCode, String licenseNumber) {
if (stateCode == null || licenseNumber == null) {
return "";
}
if (stateCode == 'AK') {
return _validateExpression(oneToSevenNumeric, licenseNumber, "Must be 1-7 numeric");
}
if (stateCode == 'AL') {
return _validateExpression(sevenNumeric, licenseNumber, "Must be 7 numeric");
}
if (stateCode == 'AR' || stateCode == 'MS') {
return _validateExpression(nineNumeric, licenseNumber, "Must be 9 numeric");
}
if (stateCode == 'AZ') {
if (nineNumeric.hasMatch(licenseNumber)) {
return "";
}
if (oneAlpha.hasMatch(licenseNumber) && eightAreNumbers.hasMatch(licenseNumber)) {
return "";
}
if (twoAlpha.hasMatch(licenseNumber) &&
threeToFiveNumeric.hasMatch(licenseNumber) &&
licenseNumber.length < 8) {
return "";
}
return "Must be 1 Alphabetic, 8 Numeric; or 2 Alphabetic, 3-6 Numeric; or 9 Numeric";
}
if (stateCode == 'CA') {
if (oneAlpha.hasMatch(licenseNumber) && oneAlphaPlusSeven.hasMatch(licenseNumber)) {
return "";
}
return "Must be 1 alpha and 7 numeric";
}
if (stateCode == 'CO' || stateCode == 'CN' || stateCode == 'CT') {
return _validateExpression(nineNumeric, licenseNumber, "Must be 9 numeric");
}
if (stateCode == 'DC') {
if (sevenNumeric.hasMatch(licenseNumber) || nineNumeric.hasMatch(licenseNumber)) {
return "";
}
return "Must be 7 - 9 numeric";
}
if (stateCode == 'DE') {
if (oneToSevenNumeric.hasMatch(licenseNumber)) {
return "";
}
return "Must be 1 - 7 numeric";
}
if (stateCode == 'FL') {
if (oneAlpha.hasMatch(licenseNumber) && twelveNumeric.hasMatch(licenseNumber)) {
return "";
}
return "Must be 1 alpha, 12 numeric";
}
if (stateCode == 'GA') {
if (sevenToNineNumeric.hasMatch(licenseNumber)) {
return "";
}
return "Must be 7 - 9 numeric";
}
if (stateCode == 'HI') {
if (nineNumeric.hasMatch(licenseNumber) || hPlusEight.hasMatch(licenseNumber)) {
return "";
}
return "Must 'H' + 8 numeric; 9 numeric";
}
if (stateCode == 'ID') {
if (nineNumeric.hasMatch(licenseNumber) ||
sixNumeric.hasMatch(licenseNumber) ||
(twoAlpha.hasMatch(licenseNumber) && alphaPlusSixNumeric.hasMatch(licenseNumber))) {
return "";
}
return "Must 9 numbers or 6 numbers; or 2 char, 6 numbers ";
}
if (stateCode == 'IL') {
if (oneAlpha.hasMatch(licenseNumber) && elevenNumeric.hasMatch(licenseNumber)) {
return "";
}
return "Must 1 character 11 numbers";
}
if (stateCode == 'IN') {
if (tenNumeric.hasMatch(licenseNumber) || nineNumeric.hasMatch(licenseNumber)) {
return "";
}
return "Must be 9-10 numbers";
}
if (stateCode == 'IA') {
if (nineAlphaChars.hasMatch(licenseNumber) || nineNumeric.hasMatch(licenseNumber)) {
return "";
}
return "Must be 9 alpha numbers";
}
if (stateCode == 'KS' || stateCode == 'KY') {
if (nineNumeric.hasMatch(licenseNumber) ||
(oneAlpha.hasMatch(licenseNumber) &&
eightAreNumbers.hasMatch(licenseNumber) &&
licenseNumber.length == 9)) {
return "";
}
return "Must be 1 alpha and 8 numeric";
}
if (stateCode == 'LA') {
if (nineNumeric.hasMatch(licenseNumber) == true) {
return "";
}
return "Must be 9 numeric";
}
if (stateCode == 'ME') {
if (sevenNumeric.hasMatch(licenseNumber) || sevenPlusX.hasMatch(licenseNumber)) {
return "";
}
return "Must be 7 numeric";
}
if (stateCode == 'MD' || stateCode == 'MI' || stateCode == 'MN') {
if (oneAlpha.hasMatch(licenseNumber) && twelveNumeric.hasMatch(licenseNumber)) {
return "";
}
return "1 Alphabetic, 12 Numeric";
}
if (stateCode == 'MA') {
if ((oneAlpha.hasMatch(licenseNumber) &&
eightAreNumbers.hasMatch(licenseNumber) &&
licenseNumber.length == 9) ||
nineNumeric.hasMatch(licenseNumber)) {
return "";
}
return "Must be 1 alpha, 8 numeric; 9 numeric";
}
if (stateCode == 'MO') {
if ((oneAlpha.hasMatch(licenseNumber) &&
fiveToNineNumeric.hasMatch(licenseNumber) &&
licenseNumber.length < 11) ||
nineNumeric.hasMatch(licenseNumber)) {
return "";
}
return "1 alpha - 5-9 Numeric or 9 numeric";
}
return "Invalid state code";
}
static String _validateExpression(RegExp expression, String value, String error) =>
expression.hasMatch(value) ? "" : error;
}

Related

The code gives an output of null instead of desired output, How can I fix the problem?

void main() {
// Object? obj = "Pre Null Safe Dart";
// showString(obj as String);
print(Rectangle().calculateArea());
print(Coffee().checkTemp());
}
class Rectangle {
double? height;
double? length;
double? breadth;
constructor() {
length = 10.7;
height = 6;
breadth = 45;
}
The values where set to null
calculateArea() {
if (length != null && height != null) {
return length! * height!;
}
}
calcualteVolume() {
if (length != null && height != null && breadth != null) {
return length! * height! * breadth!;
}
}
}
I think it because the variables in the class were set to null that is
why I am getting the output.
class Coffee {
String? temperature;
void heat() {
temperature = 'hot';
}
void chill() {
temperature = 'cold';
}
checkTemp() {
if (temperature != null) {
print('Ready to surf' + temperature! + "!");
}
}
String surf() => temperature! + "coffee";
}
Connecting to VM Service at http://127.0.0.1:58237/Gt-9FUCQakA=/
2
null
Exited
That is the output above

OpenXML not replacing FieldCode which having more than 41characters as display text not with result values

While a Field Code has more than 40 characters then OpenXML does not replace FieldCode with result values also Formating is not getting applied for the same. The below is working fine filed codes which have up to 40 characters but failed for more than 40 characters.
var format = "";
foreach (var paragraph in wordDocument.MainDocumentPart.RootElement.Descendants())
{
foreach (FieldCode fieldCode in paragraph.Descendants())
{
if (!String.IsNullOrEmpty(fieldCode.InnerText) && fieldCode.InnerText.Trim() != null && fieldCode.InnerText.Trim() != ""
&& (fieldCode.InnerText.Contains('#') || fieldCode.InnerText.Contains('#')))
{
if (fieldCode.InnerText.Contains('#'))
{
var indexofsymbol = fieldCode.InnerText.IndexOf('#') + 1;
format = fieldCode.InnerText.Substring(indexofsymbol, fieldCode.InnerText.Length - indexofsymbol);
}
else if (fieldCode.InnerText.Contains('#'))
{
var indexofsymbol = fieldCode.InnerText.IndexOf('#') + 1;
format = fieldCode.InnerText.Substring(indexofsymbol, fieldCode.InnerText.Length - indexofsymbol);
}
Run xxxfield = (Run)fieldCode.Parent;
Run rBegin = xxxfield.PreviousSibling<Run>();
Run rSep = xxxfield.NextSibling<Run>();
Run rText = rSep.NextSibling<Run>();
Run rEnd = rText.NextSibling<Run>();
if (null != xxxfield)
{
Text t = rEnd.GetFirstChild<Text>();
t = xxxfield.Descendants<Text>().FirstOrDefault();
if (t == null)
t = rText.GetFirstChild<Text>();
if (t != null)
{
var fieldName = t.Text.ToString().Substring(1, t.Text.Length - 2);
if (mergeFields.TryGetValue(fieldName, out dictValue))
{
if (fieldCode.InnerText.Contains('#'))
{
DateTime date = DateTime.Parse(dictValue);
t.Text = date.ToString(format); //Convert.ToDateTime(dictValue).ToString(format);
}
else if (fieldCode.InnerText.Contains('#'))
{
t.Text = Convert.ToDouble(dictValue).ToString(format);
}
}
}
}
}
}
}

Check if brackets are balanced in a string containing only brackets in Dart

Given a string s containing just the characters (, ), {, }, [ and ], determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Example 1:
Input: s = "()", Output: true
Example 2:
Input: s = "()[]{}", Output: true
Example 3:
Input: s = "(]", Output: false
isnt the most short answer but a readable:
void main() {
isValid(String s) {
var type1 = true;
var type2 = true;
var type3 = true;
var array = [];
for (var char in s.split('')) {
switch (char) {
case '(':
type1 = false;
array.add('type1');
break;
case ')':
type1 = array.isEmpty ? false : array.removeLast() == 'type1';
break;
case '[':
type2 = false;
array.add('type2');
break;
case ']':
type2 = array.isEmpty ? false : array.removeLast() == 'type2';
break;
case '{':
type3 = false;
array.add('type3');
break;
case '}':
type3 = array.isEmpty ? false : array.removeLast() == 'type3';
break;
default:
break;
}
}
return type1 && type2 && type3;
};
print(isValid('()[]{}')); //true
print(isValid('([])')); //true
print(isValid('([])]')); //false
print(isValid('([)]')); //false
}
Here are two different solutions in dart:
main() {
print(isValid("()[]{}")); // true
print(isValid("()[){}")); // false
print(isValid("{{)){")); // false
print(isValid("(){}()")); // true
print(isValid("[][]()")); // true
print(isValid("{{()([][{{{}}")); // false
print(isValid("{(({[[{([[[]]])}]]}))}")); // true
print("\n");
print("Soltion 2");
print(isValidSolution2("()[]{}")); // true
print(isValidSolution2("()[){}")); // false
print(isValidSolution2("{{)){")); // false
print(isValidSolution2("(){}()")); // true
print(isValidSolution2("[][]()")); // true
print(isValidSolution2("{{()([][{{{}}")); // false
print(isValidSolution2("{(({[[{([[[]]])}]]}))}")); // true
}
bool isValid(String s) {
List invalid_combo_strings = ["{]", "{)", "[}", "[)", "(}", "(]"];
List invalid_start_strings = ["}", "]", ")"];
List invalid_end_strings = ["{", "[", "("];
if (s.length % 2 != 0) {
return false;
}
if (invalid_start_strings.contains(s[0]) ||
invalid_end_strings.contains(s[s.length - 1])) {
return false;
}
return !invalid_combo_strings.any((v) => s.contains(v));
}
// solution2
isValidSolution2(String s) {
List openBrackets = ["{", "(", "["];
List closeBrackets = ["}", ")", "]"];
List validatorList = [];
if (s.isEmpty) {
return true;
}
for (String c in s.split('')) {
// add the first character if validator
// list is
// empty
if (validatorList.isNotEmpty && closeBrackets.contains(c)) {
if (openBrackets[closeBrackets.indexOf(c)] != validatorList.last) {
// at most one falsy condition defaulted it
return false;
} else {
validatorList.removeLast();
}
} else {
validatorList.add(c);
}
}
// print(validatorList);
return validatorList.isEmpty;
}
sequence = input("sequence: ")
def bracetCorrect(sequence):
while True:
if '()' in sequence:
sequence = sequence.replace('()','')
elif '[]' in sequence:
sequence = sequence.replace('[]','')
elif '{}' in sequence:
sequence = sequence.replace('{}','')
else:
return not sequence
**
I think it will help you:
**
void main() {
print(isValid("()[]{}(([[[]]]))"));
}
isValid(String str) {
var isValidSymbol = true;
var tmpStr = "";
if(str.length % 2 != 0) {
return false;
}
for(int i = 0; i < str.length; i++) {
var tmpChr = str[i];
if(tmpChr == "(" || tmpChr == "{" || tmpChr == "[") {
tmpStr += tmpChr;
} else {
if(tmpChr == ")" && tmpStr[tmpStr.length - 1] != "(") {
isValidSymbol = false;
} else if(tmpChr == "}" && tmpStr[tmpStr.length - 1] != "{") {
isValidSymbol = false;
} else if(tmpChr == "]" && tmpStr[tmpStr.length - 1] != "[" ) {
isValidSymbol = false;
} else {
tmpStr = tmpStr.substring(0, tmpStr.length - 1);
}
}
}
return isValidSymbol;
}
you may check this, but it's written in python
# Given a string s containing just the characters '(', ')', '{', '}', '[' and ']',
# determine if the input string is valid.
# An input string is valid if: Open brackets must be closed by the same type of brackets.
# Open brackets must be closed in the correct order.
import re
def isValid(s: str) -> bool:
if (s == ''):
return True
elif not ((s.count('(') - s.count(')')) == 0 and (s.count('[') - s.count(']')) == 0 and (s.count('{') - s.count('}')) == 0):
return False
else:
_result = [re.search(pattern, s)
for pattern in ['\((.)*\)', '\[(.)*\]', '\{(.)*\}']]
_result = ['' if _result[i] is None else _result[i].group()[1:-1]
for i in range(len(_result))]
return isValid(_result[0]) and isValid(_result[1]) and isValid(_result[2])
if __name__ == '__main__':
print(isValid('([]){'))
print(isValid('[]'))
print(isValid('(]'))
print(isValid('([)]'))
print(isValid('{[]}'))
print(isValid('({()}{[}])'))
void main() {
// Input: s = "()"
// Output: true
// Input: s = "()[]{}"
// Output: true
bool check = validParantheses('()[]{}{}]{');
print(check);
}
bool validParantheses(String paran) {
if (paran.length % 2 != 0) {
return false;
} else {
for (var i = 0; i < paran.length; i += 2) {
var firstChar = paran[i];
var secondChar = paran[i + 1];
var closingChar = returnClosingParan(firstChar);
if (closingChar != secondChar) {
return false;
}
}
return true;
}
}
returnClosingParan(paran) {
switch (paran) {
case '(':
return ")";
case '[':
return "]";
case '{':
return "}";
default:
return;
}
}

If-statement with NSMutableString hasprefix phone number (Beginner)

Hey I don't succeed to make a functional if-statement with my NSString
j is ABMultiValueGetCount(phones).
I've three cases : j=0, j=1, j=2...
I would like that when j = 0 or 1 or 2, that doesn't take number with prefix 02...
if j has number with prefix 06, save this number.
if j has number with other prefix save it, except if number with prefix 06 is already saved.
I tried to make this code, but it doesn't work, I don't know where is my error :
if (j == 0) {
if ([phoneNumber hasPrefix:#"02"]) {}
else
if ([phoneNumber hasPrefix:#"06"]) {
person.number = phoneNumber;
}
else
{
if ([phoneNumber length] == 0)
{
person.number = phoneNumber;
}
}
}
if (j == 1) {
if ([phoneNumber hasPrefix:#"02"]) {}
else
if ([phoneNumber hasPrefix:#"06"]) {
person.number = phoneNumber;
}
else
{
if ([phoneNumber length] == 0)
{
person.number = phoneNumber;
}
}
}
if (j == 2) {
if ([phoneNumber hasPrefix:#"02"]) {}
else
if ([phoneNumber hasPrefix:#"06"]) {
person.number = phoneNumber;
}
else
{
if ([phoneNumber length] == 0)
{
person.number = phoneNumber;
}
}
}
This seems to be the problem (it should be != instead):
if ([phoneNumber length] == 0)
To make the code simpler I would just do something like this - should be the same result:
if (j >= 0 && j < 3 && ![phoneNumber hasPrefix:#"02"] && (![person.number hasPrefix:#"06"] || [phoneNumber hasPrefix:#"06"])) {
person.number = phoneNumber;
}

LINQ Query using if condition and && Operation

Controller Method for Search
[HttpPost]
public ActionResult Search(string cno, string fname, string lname, string male, string female, string istateid, string icityid, string professionid, string educationid)
{
var db = new clubDataContext();
var query = db.M_Registarions.Where((x=> x.M_ContactNo ==(cno??x.M_ContactNo) && x.M_Fname == (fname ?? x.M_Fname) && x.M_Lname==(lname ?? x.M_Lname) && x.M_Gender == (male??x.M_Gender));
if(istateid != "")
{
int stateid1 = Convert.ToInt32(istateid);
query = query.Where(x=> x.M_StatteId == stateid1);
}
if(icityid != "")
{
int cityid1 = Convert.ToInt32(icityid);
query = query.Where(x=> x.M_CityId == cityid1);
}
if(professionid != "")
{
int professionid1 = Convert.ToInt32(professionid);
query = query.Where(x=> x.P_id == professionid1);
}
if(educationid != "")
{
int educationid1 = Convert.ToInt32(educationid);
query = query.Where(x=> x.P_id == educationid1);
}
if (!query.Any())
{
ViewBag.Count = 0;
}
else
{
var result = query.ToList();
//var search_query = from p in db.M_Registarions where (x => x.M_Fname.Contains(fname ?? x.M_Fname) || x.M_Lname.Contains(lname ?? x.M_Lname)) select p;
ViewBag.SearchResult = result;
ViewBag.Count = 1;
}
return PartialView("SearchResult");
}
Here I am using OR operation in cno, firstname and last name. I want to use &&(And) operation instead of ||(OR). But problem is I have to check for NULL or Space, that I have done in stateid, cityid , professionid and educationid. So how to use if condition in first where? var query = db.M_Registration.Where(if{}) Like this?
Use blocs {} and "return" to put a more complex expression
For example :
db.M_Registration.Where(p =>
{
if{ // my condition... }
return p.Name == name
else
return p.Name == ...
});
You could try this.
[HttpPost]
public ActionResult Search(string cno, string fname, string lname, string male, string female, string istateid, string icityid, string professionid, string educationid)
{
var db = new clubDataContext();
var query = db.M_Registarions.Where((x=> x.M_ContactNo ==(cno??x.M_ContactNo) && x.M_Fname == (fname ?? x.M_Fname) && x.M_Lname==(lname ?? x.M_Lname) && x.M_Gender == (male??x.M_Gender));
if(IntValue(istateid).HasValue)
{
query = query.Where(x=> x.M_StatteId == IntValue(istateid).Value);
}
if(IntValue(icityid).HasValue)
{
query = query.Where(x=> x.M_CityId == IntValue(icityid).Value);
}
if(IntValue(professionid).HasValue)
{
query = query.Where(x=> x.P_id == IntValue(professionid).Value);
}
if(IntValue(educationid).HasValue)
{
query = query.Where(x=> x.P_id == IntValue(educationid).Value);
}
if (!query.Any())
{
ViewBag.Count = 0;
}
else
{
var result = query.ToList();
//var search_query = from p in db.M_Registarions where (x => x.M_Fname.Contains(fname ?? x.M_Fname) || x.M_Lname.Contains(lname ?? x.M_Lname)) select p;
ViewBag.SearchResult = result;
ViewBag.Count = 1;
}
return PartialView("SearchResult");
}
public int? IntValue(string input)
{
int temp;
if (int.TryParse(input, out temp))
{
return temp;
}
return null;
}
I think you could get the result you want and avoid having tons of ifs, by trying the following query:
var query =
db.M_Registarions.Where(
x =>
x.M_ContactNo == (cno ?? x.M_ContactNo) && x.M_Fname == (fname ?? x.M_Fname)
&& x.M_Lname == (lname ?? x.M_Lname) && x.M_Gender == (male ?? x.M_Gender)
&& (string.IsNullOrEmpty(istateid) || x.M_StatteId == Convert.ToInt32(istateid))
&& (string.IsNullOrEmpty(icityid) || x.M_CityId == Convert.ToInt32(icityid))
&& (string.IsNullOrEmpty(professionid) || x.P_id == Convert.ToInt32(professionid))
&& (string.IsNullOrEmpty(educationid) || x.P_id == Convert.ToInt32(educationid)));

Resources