New Aurelia Validation ! equals(expectedValue) - aurelia

The old way:
this.validator = this.validation.on(this)
.ensure('baseContent.RedirectFrom')
.isNotEmpty()
.ensure('baseContent.RedirectTo')
.isNotEmpty()
.isNotEqualTo(() => { return this.baseContent.RedirectFrom }, 'Redirect from');
});
isNotEquals doesn't seem to exist in the new validation there is a equals(expectedValue)
I have considered doing a custom validation element however struggled as it passed through 'RedirectFrom' as undefined.
ValidationRules.customRule('notEqualTo',
(value, obj, otherValue) => {
return value === null || value === undefined || value === '' || otherValue === null || otherValue === undefined || otherValue === ''|| value === otherValue;
},
"must not match");
.ensure('RedirectTo').required().satisfiesRule('notEqualTo', this.baseContent.RedirectFrom)
.ensure('RedirectTo').required().satisfiesRule('notEqualTo', this.RedirectFrom)
.ensure('RedirectTo').required().satisfiesRule('notEqualTo', RedirectFrom)
Anyone see anything I'm missing?

obj[propertyName]
CustomValidation.js
ValidationRules.customRule('mustNotMatchValue',
(value, obj, valueToNotMatch) => {
return value === null || value === undefined || value === '' || obj[valueToNotMatch] === null || obj[valueToNotMatch] === undefined || obj[valueToNotMatch] === '' || value !== obj[valueToNotMatch];
},
"must not match ${$config.valueToNotMatch}",
(valueToNotMatch) => ({ valueToNotMatch }));
baseContent.js
.ensure('RedirectTo').required().satisfiesRule('mustNotMatchValue', 'RedirectFrom');

Related

how to stop a function in if statement in react native?

I want to use if statement in a function such that **"if there is x ,don't continue function" ** "else ,continue the function"....
my code is like below,i dont know why it continue doing the function!(it create calendar)
plz help me
const calendars = await Calendar.getCalendarsAsync(
Calendar.EntityTypes.EVENT
);
const filterdcalender = calendars.filter((e) => e.name === "new Calendar");
if (filterdcalender ==! undefined || filterdcalender ==! null) {
console.log('✅ Calender already exists');
console.log({ filterdcalender });
return;
} else{const defaultCalendarSource =
Platform.OS === 'ios'
? await getDefaultCalendarSource()
: { isLocalAccount: true, name: 'new Calendar' };
// ///////////////////////////////////////////////////new calendar
const newCalendarID = await Calendar.createCalendarAsync({
title: 'Title New Calendar',
color: 'blue',
entityType: Calendar.EntityTypes.EVENT,
sourceId: defaultCalendarSource.id,
source: defaultCalendarSource,
name: 'name New Calendar',
ownerAccount: 'personal',
accessLevel: Calendar.CalendarAccessLevel.OWNER,
});
console.log(`Your new calendar ID is: ${newCalendarID}`);
}}
First of all a ==! b isn't doing what you probably think it does. Because semantically it's equivalent to a == (!b). Use !== instead.
Second Array.filter() will never return null or undefined. It will always return an array (which may be empty if no value meeting the condition is found). Thus filteredcalender !== null || fillteredcalendar !== undefined will always be true
You could either check the length of the filtered array
const filterdcalendar = calendars.filter((e) => e.name === "new Calendar");
if (filteredcalendar.length > 0) {
//calendar already exists
return;
}
else {
//create new calendar
}
Or you could make use of Array.find()
const filterdcalendar = calendars.find((e) => e.name === "new Calendar");
if (filteredcalendar !== undefined) {
//calendar already exists
return;
}
else {
//create new calendar
}

Checking user existence in vue when editing

I am trying to check the user existence in vue with vuetify inputs when someone tries to edit a User. If the username already exists, then I throw an error, except if this username is the old username, if the user being edited in the moment didn't have his name changed.
But something in the mode It calls my function seems broken but I don't know why, I've put the function in the rules:
nameRules: [
v => !!v || 'Obrigatory field',
v => (v && (v.length <= 20 && v.length >= 2)) || 'Less than 20 and more than 2 characters',
v => ( v && (/^[a-z0-9]+$/.test(v))) || 'Only digits and lowercase letters',
v => ( v && this.checkUserExistence(v)) || 'User already exists'
]
The function:
checkUserExistence(v){
this.usersdata.some(user => {
if(user.username != this.oldusername){
return user.username == v
}
else {
return true
}
})
It looks like it is ignoring the true/false statements and showing the error anyway!
},
I was doing it wrongly. The right answer:
checkUserExistence(v){
return this.oldusername !== v && this.usersdata.some(user => user.username === v)
},
And the rule:
v => (v && !this.checkUserExistence(v)) || 'Nome de usuário já existe'

How can I find the city with spaces or accents like in the documentation geo.api.gouv using vuejs and axios?

I use this API :
https://geo.api.gouv.fr/decoupage-administratif/communes
It works really good but the problem is that if I'm searching a city (commune) like : "Saint-Étienne" I have to write exactly "Saint-Étienne". I would like to find this city for example without space : "saint étienne" or accent : "saint etienne".
In the documentation it's good.
But in my project in Vue.Js with Axios I can't find solutions. The v-select needs the exact writing.
Here is the input :
<v-autocomplete
v-else
#input="inputCity('departureCity', 'departureDepartment', selectedArrayCityDeparture)"
:loading="loading"
:items="citiesDeparture"
:search-input.sync="searchCitiesDeparture"
v-model="selectedArrayCityDeparture"
:rules="[
(value) => searchCitiesDeparture !== null || $t('form.validation.theDepartureCity') + ' ' + $t('isRequired')
]"
text
hide-no-data’
required
:label="$t('form.departureCity')"
:no-data-text="$t('noDataAvailable')"
/>
methods :
inputCity(cityType, departmentType, index) {
if (index !== null && this.responseCities[index] !== undefined) {
this.form[cityType] = this.responseCities[index].nom;
this.form[departmentType] = this.responseCities[index].codeDepartement;
}
},
querySelections(q, cities) {
this.$axios.get(this.apiRoutes.gouv.cities(q)).then(
response => {
this.loading = false;
this[cities] = _.map(response.data, function (item, i) {
return ({ text: item.nom + ' (' + item.codeDepartement + ')' , value: i });
});
this.responseCities = response.data;
}
)
},
watch :
search (val) {
val && val !== this.select && this.querySelections(val)
},
searchCitiesArrival(val) {
if (val !== null && val !== undefined && val.length > 1 && !(this.selectedArrayCityArrival !== null && this.citiesArrival[this.selectedArrayCityArrival] !== undefined && this.citiesArrival[this.selectedArrayCityArrival].text === val)) {
this.querySelections(val, "citiesArrival");
}
},
searchCitiesDeparture(val) {
if (val !== null && val !== undefined && val.length > 1 && !(this.selectedArrayCityDeparture !== null && this.citiesDeparture[this.selectedArrayCityDeparture] !== undefined && this.citiesDeparture[this.selectedArrayCityDeparture].text === val)) {
this.querySelections(val, "citiesDeparture");
}
}
data :
citiesDeparture: [],
citiesArrival: [],
responseCities: [],
call Api :
gouv: {
cities: function (name) {
return ('https://geo.api.gouv.fr/communes?nom=' + name + '&fields=&format=json&geometry=centre"');
}
},
How can I find the city with spaces or accents like in the documentation ?

React Native:How to wait till a series of setState function to return before executing the next block of code?

setState in reactnative is asynchronous and I have a series of setState statements in my code and I want the code after these setState statements execute only after all the setState returns
Code
validate = () => {
this.changedNumber();
const reg = /^[0]?[789]\d{9}$/;
if (this.state.spaceName == null || this.state.spaceName =='') {
this.setState({
error_spaceName: "Name of space is required",
})
} else if (this.state.spaceName.length < 3) {
this.setState({
error_spaceName: "Name of space should be of minimum 3 character length",
})
}
else {
this.setState({
error_spaceName: null,
})
}
if (this.state.code === null || this.state.code === '') {
this.setState({
error_phone: "Phone Number is required",
})
} else if (isValidNumber(Number(this.state.code)) === false) {
this.setState({
error_phone: "Contact number should be a Kuwait number",
})
}
else {
this.setState({
error_phone: null,
})
}
if (this.state.error == null && this.state.error_spaceName == null && this.state.error_phone == null) {
this.props.navigation.navigate("LocationScreen")
}
}
What happnes here is that
if (this.state.error == null && this.state.error_spaceName == null && this.state.error_phone == null) {
this.props.navigation.navigate("LocationScreen")
}
this part of code gets executed before all the setState returns .I want to wait till all the setStates returns before checking the conditions? What's the proper way to acheieve this?
You are't able to use was updated state after setState in one block , so because you use class components , you are able to use componentDidUpdate for solving it :
//...
componentDidUpdate(prevProps, prevState){
if (prevState.error != this.state.error
|| prevState.error_spaceName != this.state.error_spaceName
|| prevState.error_phone != this.state.error_phone){
if (this.state.error == null && this.state.error_spaceName == null && this.state.error_phone == null) {
this.props.navigation.navigate("LocationScreen")
}
}
}
//...

Manipulating props using default in vuejs

Basically, I have very less edge cases where I need to change the value of props on init like so,
props : {
columnName : String,
setValue: {
validator: function (value) {
//enum edge cases
let _value = value;
if(value === 'YES' || value === 'ACTIVE'){
value = 0;
}
else if(value === 'NO' || value === 'VOID'){
value = 1;
}
console.log(_value);
return _value;
}
}
},
Is this possible, I did try this but it is still sending the actual values instead of 0/1.
You could try to return 'value' rather than '_value'.
However, I believe this is a job for a computed property, rather than trying to manipulate the prop directly.
computed:{
computedSetValue(){
if(this.setValue === 'YES' || this.setValue === 'ACTIVE'){
return 0
}
else if(this.setValue=== 'NO' || this.setValue=== 'VOID'){
return 1
}
return 0
}
}
Then, you may use this.computedSetValue as you do this.setValue