Checking for null in edit text with for loop - list

I want to check for empty values ​​in edit text using for loop, I don't want to repeat code while doing this. I tried this but got an error. Can you help me
binding.apply {
val editTextList: ArrayList<EditText> = ArrayList()
editTextList.add(binding.etRegistedFullname)
editTextList.add(binding.etRegistedEmail)
editTextList.add(binding.etRegistedAge)
editTextList.add(binding.etRegistedPassword)
editTextList.add(binding.etRegistedConfirmpassword)
editTextList.add(binding.etRegistedPhone)
//Bu for dögüsü sayaseinde 15 satır koddan kurtuldum
for (item in editTextList) {
// Toast.makeText(this#RegisterActivity,item.id.toString(),Toast.LENGTH_SHORT).show()
when {
TextUtils.isEmpty(editTextList.get(item.id).text.toString().trim { it <= ' ' }) -> {
editTextList.get(item.id).error = "Cannot be blank"
editTextList.get(item.id).requestFocus()
}
else -> {
if (isValidPassword(etRegistedPassword.text.toString().trim())) {
if (etRegistedPassword.text.toString().equals(etRegistedConfirmpassword.text.toString())) {
val user = getPerson()
authcreateUser(user)
} else {
Toast.makeText(
this#RegisterActivity,
"password and confirm password must be the same",
Toast.LENGTH_SHORT
).show()
}
} else {
etRegistedPassword.setError("At least one number, one lowercase letter, at least one uppercase letter, no spaces and a minimum of 8 characters")
etRegistedPassword.requestFocus()
}
}
}
}
}

Since you're code is already wrapped in binding.apply, you don't have to keep typing binding.. And it's easier to create a list using listOf than what you're doing by creating an empty ArrayList and then filling it one by one.
This code of yours doesn't make sense:
editTextList.get(item.id)
item is already an EditText so you don't need to get it from the list again. List.get is going to look for the item at that index in the array, which has no relation at all to the view's ID.
binding.apply {
val editTextList = listOf(
etRegistedFullname,
etRegistedEmail,
etRegistedAge,
etRegistedPassword,
etRegistedConfirmpassword,
etRegistedPhone
)
//Bu for dögüsü sayaseinde 15 satır koddan kurtuldum
for (item in editTextList) {
// Toast.makeText(this#RegisterActivity,item.id.toString(),Toast.LENGTH_SHORT).show()
when {
TextUtils.isEmpty(item.text.toString().trim { it <= ' ' }) -> {
item.error = "Cannot be blank"
item.requestFocus()
}
else -> {
if (isValidPassword(etRegistedPassword.text.toString().trim())) {
if (etRegistedPassword.text.toString().equals(etRegistedConfirmpassword.text.toString())) {
val user = getPerson()
authcreateUser(user)
} else {
Toast.makeText(
this#RegisterActivity,
"password and confirm password must be the same",
Toast.LENGTH_SHORT
).show()
}
} else {
etRegistedPassword.setError("At least one number, one lowercase letter, at least one uppercase letter, no spaces and a minimum of 8 characters")
etRegistedPassword.requestFocus()
}
}
}
}
}
I didn't check the logic of your code besides that.

Related

How to remove a specific object from a list in dart/flutter?

I have a list called selected list of type dynamic and it holds a list of objects, each objects contains from a teacher ID & index.
I want to check if this list contains the same Id & index, if it does i want to remove this object from the list.
here is my code ....
void addTeacher(int teacherId, int index) {
if (this.selectedList.contains({ **/// the problem is here** })) {
this.selectedList.remove({teacherId, index});
this.myColor = Colors.grey;
print('removed teacher => ${teacherId.toString()}');
} else {
this.selectedList.add({teacherId, index});
this.myColor = AsasColors().blue;
print('added teacher => ${teacherId.toString()}');
}
notifyListeners();
print(selectedList);
}
how can i achive this ?
Contains and remove use the == operator which in this case will return false because unless you override it for a specific class it will compare by reference.
You can use indexWhere to find out if an item is in a list based on a compare function like that (if the function returns -1 the item is not on the list:
// Index different than -1 means the item is found somewhere in the list
final teacherIndex = this.selectedList.indexWhere((teacher) => teacher['teacherId'] == teacherId);
if (teacherIndex != -1) {
this.selectedList.removeAt(teacherIndex);
this.myColor = Colors.grey;
print('removed teacher => ${teacherId.toString()}');
} else {
...
}
I have implemented it and it worked fine
[The code]
[The output:]
This is the written code:
class Subject {
int? teacherID;
int? subjectID;
Subject(this.teacherID, this.subjectID);
#override
String toString() => "Subject {teacherID: $teacherID, subjectID: $subjectID";
//TODO: Change your needed criteria here..
#override
bool operator ==(Object other) =>
other is Subject &&
teacherID == other.teacherID &&
subjectID == other.subjectID;
}
void addSubject(List<Subject> list, Subject subject) {
if (list.contains(subject)) {
list.remove(subject);
} else {
list.add(subject);
}
}
void main() {
List<Subject> selectedList =
List.generate(10, (index) => Subject(index + 1, index + 1));
print("SelectedList = $selectedList");
addSubject(selectedList, Subject(11, 11));
addSubject(selectedList, Subject(11, 12));
addSubject(selectedList, Subject(12, 11));
addSubject(selectedList, Subject(12, 12));
print("SelectedList2 = $selectedList");
addSubject(selectedList, Subject(12, 12));
print("SelectedList3 = $selectedList");
}
Sincerely, accept the answer if it worked for you.

How do I rewrite regex in golang to work around no support for positive lookaheads? [duplicate]

I am trying to write password validation function with regexp and don't know how to do it.
The regex package provided by the standard API of the Go language is different to other languages.
Have someone an idea, how this regexp pattern should looks like?
The pattern should validate:
/*
* Password rules:
* at least 7 letters
* at least 1 number
* at least 1 upper case
* at least 1 special character
*/
That's actually impossible since Go's regex doesn't support backtracking.
However, it's easy to implement, a simple example:
func verifyPassword(s string) (sevenOrMore, number, upper, special bool) {
letters := 0
for _, c := range s {
switch {
case unicode.IsNumber(c):
number = true
case unicode.IsUpper(c):
upper = true
letters++
case unicode.IsPunct(c) || unicode.IsSymbol(c):
special = true
case unicode.IsLetter(c) || c == ' ':
letters++
default:
//return false, false, false, false
}
}
sevenOrMore = letters >= 7
return
}
The right regexp would be... no regexp here.
You can define a custom function that would validate the password, and combine it with other frameworks helping validating a field, like mccoyst/validate (mentioned in this discussion about parameter validation)
You also have go-validator/validator whic allows to define similar validations (but I would still use a custom validator instead of one or several regexps).
Note: go regexp is based on re2, an efficient, principled regular expression library).
So the major trade offs are no back-references for example: (abc)\1 and no matching look-behinds.
In exchange you get high speed regex.
Building from a neighboring answer, I too wrote a helper function that works well for me. This one just assumes overall password length is satisfactory. Check out the following...
func isValid(s string) bool {
var (
hasMinLen = false
hasUpper = false
hasLower = false
hasNumber = false
hasSpecial = false
)
if len(s) >= 7 {
hasMinLen = true
}
for _, char := range s {
switch {
case unicode.IsUpper(char):
hasUpper = true
case unicode.IsLower(char):
hasLower = true
case unicode.IsNumber(char):
hasNumber = true
case unicode.IsPunct(char) || unicode.IsSymbol(char):
hasSpecial = true
}
}
return hasMinLen && hasUpper && hasLower && hasNumber && hasSpecial
}
isValid("pass") // false
isValid("password") // false
isValid("Password") // false
isValid("P#ssword") // false
isValid("P#ssw0rd") // true
Go Playground example
Based on #OneOfOne's answer with some error message improvement
package main
import (
"fmt"
"strings"
"unicode"
)
func verifyPassword(password string) error {
var uppercasePresent bool
var lowercasePresent bool
var numberPresent bool
var specialCharPresent bool
const minPassLength = 8
const maxPassLength = 64
var passLen int
var errorString string
for _, ch := range password {
switch {
case unicode.IsNumber(ch):
numberPresent = true
passLen++
case unicode.IsUpper(ch):
uppercasePresent = true
passLen++
case unicode.IsLower(ch):
lowercasePresent = true
passLen++
case unicode.IsPunct(ch) || unicode.IsSymbol(ch):
specialCharPresent = true
passLen++
case ch == ' ':
passLen++
}
}
appendError := func(err string) {
if len(strings.TrimSpace(errorString)) != 0 {
errorString += ", " + err
} else {
errorString = err
}
}
if !lowercasePresent {
appendError("lowercase letter missing")
}
if !uppercasePresent {
appendError("uppercase letter missing")
}
if !numberPresent {
appendError("atleast one numeric character required")
}
if !specialCharPresent {
appendError("special character missing")
}
if !(minPassLength <= passLen && passLen <= maxPassLength) {
appendError(fmt.Sprintf("password length must be between %d to %d characters long", minPassLength, maxPassLength))
}
if len(errorString) != 0 {
return fmt.Errorf(errorString)
}
return nil
}
// Let's test it
func main() {
password := "Apple"
err := verifyPassword(password)
fmt.Println(password, " ", err)
}
Below it's my implementation of the above answers with custom messages and somehow twisting to them in a good way(performance aware codes).
package main
import (
"fmt"
"strconv"
"unicode"
)
func main() {
pass := "12345678_Windrol"
// call the password validator and give it field name to be known by the user, password, and the min and max password length
isValid, errs := isValidPassword("Password", pass, 8, 32)
if isValid {
fmt.Println("The password is valid")
} else {
for _, v := range errs {
fmt.Println(v)
}
}
}
func isValidPassword(field, s string, min, max int) (isValid bool, errs []string) {
var (
isMin bool
special bool
number bool
upper bool
lower bool
)
//test for the muximum and minimum characters required for the password string
if len(s) < min || len(s) > max {
isMin = false
appendError("length should be " + strconv.Itoa(min) + " to " + strconv.Itoa(max))
}
for _, c := range s {
// Optimize perf if all become true before reaching the end
if special && number && upper && lower && isMin {
break
}
// else go on switching
switch {
case unicode.IsUpper(c):
upper = true
case unicode.IsLower(c):
lower = true
case unicode.IsNumber(c):
number = true
case unicode.IsPunct(c) || unicode.IsSymbol(c):
special = true
}
}
// append error
appendError := func(err string) {
errs = append(errs, field+" "+err)
}
// Add custom error messages
if !special {
appendError("should contain at least a single special character")
}
if !number {
appendError("should contain at least a single digit")
}
if !lower {
appendError("should contain at least a single lowercase letter")
}
if !upper {
appendError("should contain at least single uppercase letter")
}
// if there is any error
if len(errs) > 0 {
return false, errs
}
// everyting is right
return true, errs
}
There are many ways to skin a cat---The other answers seem to veer away from regex completely, so I thought I'd show my method for simple pass/fail testing of a password string, which is styled to suit my thinking. (Note that this doesn't meet the literal "7 letters" requirement in the original question, but does check overall length.) To me, this code is fairly simple and looks easier to read than doing switch statements or a bunch of if statements:
password := "Pa$$w0rd"
secure := true
tests := []string{".{7,}", "[a-z]", "[A-Z]", "[0-9]", "[^\\d\\w]"}
for _, test := range tests {
t, _ := regexp.MatchString(test, password)
if !t {
secure = false
break
}
}
//secure will be true, since the string "Pa$$w0rd" passes all the tests

std::unordered_map::count is not working in my code

I have a doubt with the solution of this question which is stated below -
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Strings["aa", "ab"] should return false and strings["aa", "aab"] should return true according to question.
Here is the code which I have attempted in the first place and I'm not getting a required output as mentioned above.
unordered_map<char,int>umap;
for(char m:magazine)
{
umap[m]++;
}
for(char r:ransomNote)
{
if(umap.count(r)<=1)
{
return false;
}
else{
umap[r]--;
}
}
return true;
}
In the above code, I have used umap.count(r)<=1 to return false if there is no key present.
For the strings ["aa","aab"], it is returning true but for strings ["aa","ab"], it is also returning true but it should return false.
Then I used another way to solve this problem by using just umap[r]<=0 in the place of umap.count(r)<=1 and it is working just fine and else all code is same.
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char,int>umap;
for(char m:magazine)
{
umap[m]++;
}
for(char r:ransomNote)
{
if(umap[r]<=0)
{
return false;
}
else{
umap[r]--;
}
}
return true;
}
I'm not able to get what i'm missing in the if condition of first code. Can anyone help me to state what I'm doing wrong in first code. Any help is appreciated.
unordered_map::count returns the number of items with specified key.
As you don't use multi_map version, you only have 0 or 1.
Associated value doesn't change presence of key in map.
To use count, you should remove key when value reaches 0:
for (char r : ransomNote) {
if (umap.count(r) == 0) {
return false;
} else {
if (--umap[r] == 0) {
umap.erase(r);
}
}
}
return true;

Regex to not allow space between words [duplicate]

I'm trying to write a regular expression to remove white spaces from just the beginning of the word, not after, and only a single space after the word.
Used RegExp:
var re = new RegExp(/^([a-zA-Z0-9]+\s?)*$/);
Test Exapmle:
1) test[space]ing - Should be allowed
2) testing - Should be allowed
3) [space]testing - Should not be allowed
4) testing[space] - Should be allowed but have to trim it
5) testing[space][space] - should be allowed but have to trim it
Only one space should be allowed. Is it possible?
To match, what you need, you can use
var re = /^([a-zA-Z0-9]+\s)*[a-zA-Z0-9]+$/;
Maybe you could shorten that a bit, but it matches _ as well
var re = /^(\w+\s)*\w+$/;
function validate(s) {
if (/^(\w+\s?)*\s*$/.test(s)) {
return s.replace(/\s+$/, '');
}
return 'NOT ALLOWED';
}
validate('test ing') // => 'test ing'
validate('testing') // => 'testing'
validate(' testing') // => 'NOT ALLOWED'
validate('testing ') // => 'testing'
validate('testing ') // => 'testing'
validate('test ing ') // => 'test ing'
BTW, new RegExp(..) is redundant if you use regular expression literal.
This one does not allow preceding and following spaces plus only one space between words. Feel free to add any special characters You want.
^([A-Za-z]+ )+[A-Za-z]+$|^[A-Za-z]+$
demo here
Working code- Inside my name.addTextChangedListener():
public void onTextChanged(CharSequence s, int start, int before, int count) {
String n = name.getText().toString();
if (n.equals(""))
name.setError("Name required");
else if (!n.matches("[\\p{Alpha}\\s]*\\b") | n.matches(".*\\s{2}.*") | n.matches("\\s.*")) {
if (n.matches("\\s.*"))
name.setError("Name cannot begin with a space");
else if (n.matches(".*\\s{2}.*"))
name.setError("Multiple spaces between texts");
else if (n.matches(".*\\s"))
name.setError("Blank space at the end of text");
else
name.setError("Non-alphabetic character entered");
}
}
You could try adapting this to your code.
var f=function(t){return Math.pow(t.split(' ').length,2)/t.trim().split(' ').length==2}
f("a a")
true
f("a a ")
false
f("a a")
false
f(" a a")
false
f("a a a")
false
Here is a solution without regular expression.
Add this script inside document.ready function it will work.
var i=0;
jQuery("input,textarea").on('keypress',function(e){
//alert();
if(jQuery(this).val().length < 1){
if(e.which == 32){
//alert(e.which);
return false;
}
}
else {
if(e.which == 32){
if(i != 0){
return false;
}
i++;
}
else{
i=0;
}
}
});
const handleChangeText = text => {
let lastLetter = text[text.length - 1];
let secondLastLetter = text[text.length - 2];
if (lastLetter === ' ' && secondLastLetter === ' ') {
return;
}
setInputText(text.trim());
};
use this
^([A-Za-z]{5,}|[\s]{1}[A-Za-z]{1,})*$
Demo:-https://regex101.com/r/3HP7hl/2

Fuzzy Matches on dijit.form.ComboBox / dijit.form.FilteringSelect Subclass

I am trying to extend dijit.form.FilteringSelect with the requirement that all instances of it should match input regardless of where the characters are in the inputted text, and should also ignore whitespace and punctuation (mainly periods and dashes).
For example if an option is "J.P. Morgan" I would want to be able to select that option after typing "JP" or "P Morgan".
Now I know that the part about matching anywhere in the string can be accomplished by passing in queryExpr: "*${0}*" when creating the instance.
What I haven't figured out is how to make it ignore whitespace, periods, and dashes. I have an example of where I'm at here - http://jsfiddle.net/mNYw2/2/. Any help would be appreciated.
the thing to master in this case is the store fetch querystrings.. It will call a function in the attached store to pull out any matching items, so if you have a value entered in the autofilling inputfield, it will eventually end up similar to this in the code:
var query = { this.searchAttr: this.get("value") }; // this is not entirely accurate
this._fetchHandle = this.store.query(query, options);
this._fetchHandle.then( showResultsFunction );
So, when you define select, override the _setStoreAttr to make changes in the store query api
dojo.declare('CustomFilteringSelect', [FilteringSelect], {
constructor: function() {
//???
},
_setStoreAttr: function(store) {
this.inherited(arguments); // allow for comboboxmixin to modify it
// above line eventually calls this._set("store", store);
// so now, 'this' has 'store' set allready
// override here
this.store.query = function(query, options) {
// note that some (Memory) stores has no 'fetch' wrapper
};
}
});
EDIT: override queryEngine function as opposed to query function
Take a look at the file SimpleQueryEngine.js under dojo/store/util. This is essentially what filters the received Array items on the given String query from the FilteringSelect. Ok, it goes like this:
var MyEngine = function(query, options) {
// create our matching query function
switch(typeof query){
default:
throw new Error("Can not query with a " + typeof query);
case "object": case "undefined":
var queryObject = query;
query = function(object){
for(var key in queryObject){
var required = queryObject[key];
if(required && required.test){
if(!required.test(object[key])){
return false;
}
}else if(required != object[key]){
return false;
}
}
return true;
};
break;
case "string":
/// HERE is most likely where you can play with the reqexp matcher.
// named query
if(!this[query]){
throw new Error("No filter function " + query + " was found in store");
}
query = this[query];
// fall through
case "function":
// fall through
}
function execute(array){
// execute the whole query, first we filter
var results = arrayUtil.filter(array, query);
// next we sort
if(options && options.sort){
results.sort(function(a, b){
for(var sort, i=0; sort = options.sort[i]; i++){
var aValue = a[sort.attribute];
var bValue = b[sort.attribute];
if (aValue != bValue) {
return !!sort.descending == aValue > bValue ? -1 : 1;
}
}
return 0;
});
}
// now we paginate
if(options && (options.start || options.count)){
var total = results.length;
results = results.slice(options.start || 0, (options.start || 0) + (options.count || Infinity));
results.total = total;
}
return results;
}
execute.matches = query;
return execute;
};
new Store( { queryEngine: MyEngine });
when execute.matches is set on bottom of this function, what happens is, that the string gets called on each item. Each item has a property - Select.searchAttr - which is tested by RegExp like so: new RegExp(query).test(item[searchAttr]); or maybe a bit simpler to understand; item[searchAttr].matches(query);
I have no testing environment, but locate the inline comment above and start using console.debug..
Example:
Stpre.data = [
{ id:'WS', name: 'Will F. Smith' },
{ id:'RD', name:'Robert O. Dinero' },
{ id:'CP', name:'Cle O. Patra' }
];
Select.searchAttr = "name";
Select.value = "Robert Din"; // keyup->autocomplete->query
Select.query will become Select.queryExp.replace("${0]", Select.value), in your simple queryExp case, 'Robert Din'.. This will get fuzzy and it would be up to you to fill in the regular expression, here's something to start with
query = query.substr(1,query.length-2); // '*' be gone
var words = query.split(" ");
var exp = "";
dojo.forEach(words, function(word, idx) {
// check if last word
var nextWord = words[idx+1] ? words[idx+1] : null;
// postfix 'match-all-but-first-letter-of-nextWord'
exp += word + (nextWord ? "[^" + nextWord[0] + "]*" : "");
});
// exp should now be "Robert[^D]*Din";
// put back '*'
query = '*' + exp + '*';