Multiple validations rule in v-text-field - vuejs2

I need to perform multiple validations on a field in vuetify, for example the identity field must have 11 characters, and all must be numeric, I am using this code but it validates the quantity and if it is numeric or not only in the first character that is written.Could you guide me how to solve this problem?
This is part of the code that I am using
<v-col cols="4" sm="4" md="4">
<v-text-field
label="Identidad*"
v-model.number="editedItem.identidad"
:rules ='inputidentidadrules'
counter="11"
error-count="2"
required/>
</v-col>
.......
export default {
data: () => {
return {
dialog: false,
search: '',
isFormValid: false,
inputidentidadrules:[
(v) => v.toString().length >=11 || 'Longitud 11 caracteres',
(v) => !isNaN(parseFloat(v)) || 'El valor debe ser numérico'
],
.......

Try below rule and remove .number from v-model ie use v-model="editedItem.identidad"
inputidentidadrules:[
(v) => /^\d+$/.test(v)||'El valor debe ser numérico',
(v) => (v && v.length > 10) || 'Longitud 11 caracteres'
],

try this one below rule is related to checking for valid 11 digit
inputidentidadrules:[(v) => /^\d{11}$/.test(v) || 'Enter valid 11 digit']

Related

vuejs pass extra parameter to function

Is it possible within Quasar Form rules to pass extra parameter?
This had to do with the following template code:
<q-field outlined v-else-if="prop.component === 'checkbox'"
class="q-gutter-sm"
v-model="dataRef[key]"
:label="prop.label"
:rules="[isCheckLimit]"
>
<q-option-group
style="margin-top:20px;"
:options="prop.options"
type="checkbox"
v-model="dataRef[key]"
/>
</q-field>
The function:
const isCheckLimit = (v) => {
return v.length > 2 || t('checked-to-much')
}
I want that number 2 to be dynamic instead of static, is it possible to pass for example a number to that function? I cant find any clear information about that?
Thank you in advance.
You have to define your rule as function in your rules array, first lets update your validation function to accept second argument, I will also set it to default value of 2:
const isCheckLimit = (v, minLength = 2) => {
return v.length > minLength || t('checked-to-much');
};
Now if you use this for your rules:
:rules="[(value) => isCheckLimit(value, 4)]"
Your validation function will use 4 for minLength instead of default 2.
Original way will also work:
:rules="[isCheckLimit]"
But will use the default value of 2 for minLength

q-input has value then only Rules will apply

If q-input has value != '' then only i want to apply the Rules like required 8 number maximum. In the below code it gives me the required input error even it's null.
<q-input
filled
name="landline"
label="Landline Phone Number"
v-model="user.landline"
placeholder="Landline Phone Number"
ref="landlinePhoneNumber"
type="number"
:maxlength="8"
:rules="[val => val!='' && val.length > 7 || 'Landline Required 8 digit']"
/>
Try to add prop lazy-rules.
By default, it's set to 'ondemand', which means that validation will be triggered only when the component’s validate() method is manually called or when the wrapper QForm submits itself. More info
You have to return true when the field is null first, then validate only if it's not null. Also, add the prop lazy-rules so that it only validates when the form field loses focus.
Here is how I did it in Vue 3, using composable and TypeScript. The form field component:
<q-input
class="q-mt-md"
filled
v-model="id_number"
label="ID Number "
type="text"
hint="Optional/Leave blank if not available"
lazy-rules
:rules="[(val) => isNumberBlankOrValid(val) || 'Invalid ID Number']"
/>
The method isNumberBlankOrValid called from the field above:
const isNumberBlankOrValid = (val: string) => {
if (val.length === 0) {
return true
}
return isValidNumber(val)
}
The isValidNumber for other fields that must be filled:
const isValidNumber = (val: string) => val && isNumeric(val)
The isNumeric method is a simple regex for validating numbers:
const isNumeric = (value: string) => {
return /^\d+$/.test(value)
}

Vue Element Table: undefined nested value crashes Chrome

I'm using a Vue Element table to display a list of objects that has an object nested in it.
"main_list":{
"id": "1",
"user": {
"username": "Bob"
}
}
I can display the username using:
<el-table-column prop="user.username" label="User" sortable />
Every now and then this page will throw an error stating that it can not read value username of undefined. This will crash Google Chrome to the extent that you have to kill all Chrome processes in the task manager. Firefox does not crash this bad. I think it goes into an infinite loop
I get the data via API, so it might be that some of the user object does not have any usernames.
So far the the only solution that I have found (I'm not sure it is a solution) is:
<el-table-column prop="username" label="User">
<template
v-if="typeof scope.row.assigned_to !== 'undefined'"
slot-scope="scope"
>{{ scope.row.assigned_to.username }}</template>
</el-table-column>
Do you have any Idea why this crash happens?
Is there a better solution than mine?
Once you fetch the list of items, you should update each one of them so that every user has a defined username - even if it is an empty string. Something like
axios.get(url).then(result =>
this.items = result.data.map(item =>
{
if(!item.user) item.user = {};
if(!item.user.username) item.user.username = '';
return item;
});
You can also try something else:
<el-table-column label="User" sortable :sort-method="sortUsers">
<template slot-scope="tbl">
{{ (tbl.row.user || {}).username || 'UNKNOWN' }}
</template>
</el-table-column>
methods:
{
sortUsers(a, b)
{
const left = (a.user || {}).username || 'UNKNOWN';
const right = (b.user || {}).username || 'UNKNOWN';
if (left < right) return -1;
if (left > right) return 1;
return 0;
}
}

How can I add 2 condition in one class vue.js 2?

My vue component is like this :
<template>
<a :class="'btn ' + [respond == 'responseFound' ? ' btn-yellow' : ' btn-default', type == 1 ? ' btn-block' : ' btn-xs center-block']">
...
</a>
</template>
I try like that, but it does not work?
You can use :class="[array, of, classes]" syntax:
<a :class="['btn', (respond === 'responseFound' ? 'btn-yellow' : 'btn-default'), (type === 1 ? 'btn-block' : 'btn-xs center-block')]">
As a bonus you don't have to worry about adding the leading spaces, Vue will handle it.
Just to keep things clean in view/template/markup, move your conditions to computed properties:
<template>
<a :class="['btn', getRespondClass, getTypeClass]">
</template>
<script>
export default {
data () {
return {
respond: '',
type: ''
}
},
computed: {
getRespondClass () {
return this.respond === 'responseFound' ? 'btn-yellow' : 'btn-default'
},
getTypeClass () {
return this.type === 1 ? 'btn-block' : 'btn-xs center-block'
}
}
}
</script>
Pretty sure the current showed answer says how you can add multiple classes on 1 condition. But if you want to have multiple conditions for your class added you can simply just do it like this:
:class="{'classname': condition_one && condition_two}"
Or you can do this:
:class="[ condition1 | condition2 ? 'className' : '']"
This checks for either of the conditions to be true. If you want to check for both replace | with &&. But if you have nothing in the else class, I think #Marnix's answer is cleaner.

Ember.js input fields

Is it possible to use standard HTML5 input fields in an Ember.js view, or are you forced to use the limited selection of built in fields like Ember.TextField, Ember.CheckBox, Ember.TextArea, and Ember.select? I can't seem to figure out how to bind the input values to the views without using the built in views like:
Input: {{view Ember.TextField valueBinding="objectValue" }}
Specifically, I'm in need of a numeric field. Any suggestions?
EDIT: This is now out of date you can achieve everything above with the following:
{{input value=objectValue type="number" min="2"}}
Outdated answer
You can just specify the type for a TextField
Input: {{view Ember.TextField valueBinding="objectValue" type="number"}}
If you want to access the extra attributes of a number field, you can just subclass Ember.TextField.
App.NumberField = Ember.TextField.extend({
type: 'number',
attributeBindings: ['min', 'max', 'step']
})
Input: {{view App.NumberField valueBinding="objectValue" min="1"}}
#Bradley Priest's answer above is correct, adding type=number does work. I found out however that you need to add some attributes to the Ember.TextField object if you need decimal numbers input or want to specify min/max input values. I just extended Ember.TextField to add some attributes to the field:
//Add a number field
App.NumberField = Ember.TextField.extend({
attributeBindings: ['name', 'min', 'max', 'step']
});
In the template:
{{view App.NumberField type="number" valueBinding="view.myValue" min="0.0" max="1.0" step="0.01" }}
et voile!
Here is my well typed take on it :
App.NumberField = Ember.TextField.extend({
type: 'number',
attributeBindings: ['min', 'max', 'step'],
numericValue: function (key, v) {
if (arguments.length === 1)
return parseFloat(this.get('value'));
else
this.set('value', v !== undefined ? v+'' : '');
}.property('value')
});
I use it that way:
{{view App.NumberField type="number" numericValueBinding="prop" min="0.0" max="1.0" step="0.01" }}
The other systems where propagating strings into number typed fields.
You may also wish to prevent people from typing any old letters in there:
App.NumberField = App.TextField.extend({
type: 'number',
attributeBindings: ['min', 'max', 'step'],
numbericValue : function (key,v) {
if (arguments.length === 1)
return parseFloat(this.get('value'));
else
this.set('value', v !== undefined ? v+'' : '');
}.property('value'),
didInsertElement: function() {
this.$().keypress(function(key) {
if((key.charCode!=46)&&(key.charCode!=45)&&(key.charCode < 48 || key.charCode > 57)) return false;
})
}
})
Credit where its due: I extended nraynaud's answer
This is how I would do this now (currently Ember 1.6-beta5) using components (using the ideas from #nraynaud & #nont):
App.NumberFieldComponent = Ember.TextField.extend
tagName: "input"
type: "number"
numericValue: ((key, value) ->
if arguments.length is 1
parseFloat #get "value"
else
#set "value", (if value isnt undefined then "#{value}" else "")
).property "value"
didInsertElement: ->
#$().keypress (key) ->
false if (key.charCode isnt 46) and (key.charCode isnt 45) and (key.charCode < 48 or key.charCode > 57)
Then, to include it in a template:
number-field numericValue=someProperty