Checking user existence in vue when editing - vue.js

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'

Related

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")
}
}
}
//...

Vue.js - Element UI - get the state of form validation

Steps to reproduce
The recurrence link is this: https://stackblitz.com/edit/typescript-vuejs-element-3kko7a
password input 2
username input 11
Change username to 2// should be able to submit, but not
Expected: formvalid = true
Validate Code here:
checkForm() {
// console.log('validate runs');
// #ts-ignore
const fields = this.$refs.ruleForm.fields;
if (fields.find((f) => f.validateState === 'validating')) {
setTimeout(() => {
this.checkForm();
}, 100);
}
this.formValid = fields.reduce((acc, f) => {
const valid = (f.isRequired && f.validateState === 'success');
const notErroring = (!f.isRequired && f.validateState !== 'error');
return acc && (valid || notErroring);
}, true);
console.log('valid:', this.$data.formValid);
}
Basically you watch ruleForm - so everytime ruleForm changes you trigger checkform - but your validtor triggers on blur after you set ruleForm so you first test then turn valid. change this into a getter:
get formValid(){
const fields = this.$refs.ruleForm.fields || [];
if (fields.find((f) => f.validateState === 'validating')) {
setTimeout(() => {
this.checkForm();
}, 100);
}
return fields.reduce((acc, f) => {
const valid = (f.isRequired && f.validateState === 'success');
const notErroring = (!f.isRequired && f.validateState !== 'error');
return acc && (valid || notErroring);
}, fields.length > 0);
}

Format Textbox input for phone number MVC

I am simply using a #Html.TextBoxFor(m => m.PhoneNumber, new { id = "phoneNo")
I am using a regex to limit it to 10 numbers only.
Is there a way I can format the textbox to appear like (555) 444-3333 while they type, but in the model it will simply be passing the 10 numbers, like 5554443333? I meant to automatically create those brackets and - while also checking using regex if they entered 10 numbers?
You can do it with jquery as Matt said at his comment, stated at this question of the site:
Phone mask with jQuery and Masked Input Plugin
Or with plain javascript, as explained by xxx here with alternatives too:
Mask US phone number string with JavaScript
List of alternatives coded for a example input called "phone":
Example code with plain javaScript:
document.getElementById('phone').addEventListener('input', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});
Example code with jQuery but without adding any new dependence():
$('#phone', '#example-form')
.keydown(function (e) {
var key = e.which || e.charCode || e.keyCode || 0;
$phone = $(this);
// Don't let them remove the starting '('
if ($phone.val().length === 1 && (key === 8 || key === 46)) {
$phone.val('(');
return false;
}
// Reset if they highlight and type over first char.
else if ($phone.val().charAt(0) !== '(') {
$phone.val('('+$phone.val());
}
// Auto-format- do not expose the mask as the user begins to type
if (key !== 8 && key !== 9) {
if ($phone.val().length === 4) {
$phone.val($phone.val() + ')');
}
if ($phone.val().length === 5) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 9) {
$phone.val($phone.val() + '-');
}
}
// Allow numeric (and tab, backspace, delete) keys only
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.bind('focus click', function () {
$phone = $(this);
if ($phone.val().length === 0) {
$phone.val('(');
}
else {
var val = $phone.val();
$phone.val('').val(val); // Ensure cursor remains at the end
}
})
.blur(function () {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});
Example code with jQuery using Masked Input Plugin:
$("#phone").mask("(99) 9999?9-9999");
$("#phone").on("blur", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 3 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") - 1, 1 );
var lastfour = move + last;
var first = $(this).val().substr( 0, 9 );
$(this).val( first + '-' + lastfour );
}
});

Add restriction based on method parameter

I have a method
List<MyType> DoQuery(bool FilterWeek) {
var result = session.QueryOver<MyType>()
.Where (r => r.isValid == 1
&& r.value1 == 2
&& r.name == "XYZ"
&& [...etc, more columns are used...]
)
// how do I go on from this point?
}
if the FilterWeek parameter is true, I want to add an extra "&& r.xyz == 1" clause to the Where criteria. If FilterWeek is false, the query is done.
How do I do that?
if (FilterWeek)
result = result.Where(r => r.xyz ==1);
//...whenever you're done, execute the query using List() or SingleOrDefault()
this:
List<MyType> DoQuery(bool FilterWeek) {
var result = session.QueryOver<MyType>()
.Where (r => r.isValid == 1
&& r.value1 == 2
&& r.name == "XYZ"
&& [...etc, more columns are used...]
);
if(FilterWeek)
result.Where(x => x.Whatever == 1)
//the query won't get executed until here
result.List();
}