How to stop Vuelidate validation after any rule returns false? - vue.js

I have this rules:
username: {
required: helpers.withMessage('Fill in required fields', required),
lettersAndDigitsOnly: helpers.withMessage(
'Username: digits and letters only',
helpers.regex(/^[0-9a-zA-Z]+$/)
),
available: helpers.withMessage(
'Username is already taken',
helpers.withAsync(usernameAvailable)
),
},
usernameAvailable is called even if lettersAndDigitsOnly returns false. I don't want next validation methods to be called if previous one returned false, how can i do this?
I need something similar to .bail() from express-validator, but in Vuelidate

Related

How to set validation schema based on condition using Yup? Formik

I'm trying to use Yup to validate data in an array. For example, this is my initialValue:
{name:'',extra:[]}
After dynamic render the form field , the initialValue will become like this:
{name:'',extra:[{label:'age',value:'',required:true}]}
I want to set the validation scheme to validate the 'value' in the object only when 'required' is true.
I use this data to mock the situation:
{name:'john',extra:[{label:'age',value:'',required:true}]};
Method that i had try:
const validationschema = yup.object().shape({
name: yup.string().required(),
extra: yup.lazy((value,index)=>{
return yup.mixed().required();
})
})
There should be an error when the user submit , because the 'value' for age is empty.
I not sure why, i can't really validate the 'value'. How do I change my validationschema so it can validate the 'value' ?
Try to validate like:
name: yup.string().required(),
extra: yup.array()
.of(
yup.object().shape({
required: yup.bool(),
value: yup.object().when('required', {
is: true,
then: yup.string().required('Please, select position')
}),
})
)
There you should check field required. If it true you validate it.

How to create correct rule for validating zero via vee-validate

"vee-validate": "^2.2.11",
"vue": "^2.5.16",
I need a simple rule, the rule should be that the input must be required,numeric and greater than 0.
So in this case, if I input 0 it validates correctly(return false), but if I input something like this 0.0 vv returns true. Even if I remove is_not:0, the result still the same.
<sui-input
type="text"
v-validate="'required|decimal|is_not:0'"
name="cellSize"
v-model="cellSize">
You could also create a custom rule, like follows.
created() {
this.$validator.extend(
'greaterThanZero',{
getMessage: field => field + ' needs to be > zero.',
validate: (value) => {
// value must be > zero
if (value > 0 ) return true;
return false;
}
});
},
then call the code on your field instance.
v-validate="'required|decimal|greaterThanZero'"
more on custom rules here:
https://vee-validate.logaretm.com/v2/guide/custom-rules.html#creating-a-custom-rule
or you could also use this following style (if you were going to add more than one rule for example). Here the code would be inserted in the area where you do your imports, i.e. directly after the script tag.
import { Validator } from 'vee-validate';
Validator.extend(
'greaterThanZero',
(value) => {
// value must be > zero
if (value > 0 ) return true;
return false;
}
);
let instance = new Validator({ greaterThanZeroField: 'greaterThanZero' });
you can now add a second rule to the style directly above using the following code:
instance.extend('greaterThan1Million', {
getMessage: field => field +' needs to be > 1,000,000',
validate: value => (value > 1000000 ? true : false)
});
instance.attach({
name: 'greaterThan1MillionField',
rules: 'greaterThan1Million'
});
again that second rule could be called as follows:
v-validate="'required|decimal|greaterThan1Million'"
I found this solution(to leave everything greater than 0)
<sui-input
type="text"
v-validate="{ required: true, regex: /^(?=.*[1-9])\d+(\.\d+)?$/ }"
name="cellSize"
v-model="cellSize">
</sui-input>
Did you try to use a regex to exclude 0 ?
Example:
<input v-validate="{ required: true, regex: /[1-9]*/ }">

what is the proper way to validate all elements of an array in the query parameters even with 1 element with express-validator?

Using express-validator version 5.3.0.
I love the new syntax and I want to validate that a query parameter is valid. That parameter can be an array (as in repeat parameter).
The issue I have is that when only 1 element is passed, the framework seems to just consider it a string and the error message(s) is(are) a bit cumbersome.
with this configuration:
checkSchema([
{
foo: {
in: 'query',
isAlphanumeric: true,
optional: true,
errorMessage: 'Invalid foo'
}
}])
with the url http://server/api?foo=bar&foo=not bar I get the following error:
{
"location": "query",
"param": "foo[1]",
"value": "not bar",
"msg": "Invalid foo"
}
which seems correct.
However with the url http://server/api?foo=not bar I get the following error:
{
"location": "query",
"param": "foo[3]",
"value": " ",
"msg": "Invalid foo"
}
It's not a huge deal, but the foo[3] param is a bit misleading as technically is either just foo or foo[0].
I tried with isArray: true like below, but no luck:
foo: {
in: 'query',
isArray: true,
isAlphanumeric: true,
optional: true,
errorMessage: 'Invalid foo',
},
But that seems to actually ignore the second foo parameter (because technically a string is an array of characters?).
And with the single parameter version foo=no bar it shows the error message twice (I assume because the validator fails for both isArray and isAlphanumeric?)
Alright, so, it looks like express-validator was updated since then and now provides a toArray sanitizer.
So now, I can write the following:
checkSchema([
{
foo: {
in: 'query',
optional: true,
toArray: true,
},
'foo.*': {
in: 'query',
isAlphanumeric: true,
optional: true,
errorMessage: 'Invalid foo'
}
}])
And as an added bonus, it will now always convert queries with 1 parameter to an array of 1 value.

Field not required but if user entered a value it must be meeting some rules (vuetify rules)

I am trying to enter a validation for a field that accept url, the field not required but if user entered a value it must meet url regex.
so I tried the following code
<v-text-field height="34px" v-model="website" single-line outline placeholder="http://" :rules="urlRules"></v-text-field>
this attribute :rules="urlRules" refer to a bulk of rules that I give in my vue object
urlRules: [
v => !!v || 'required',
v => /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi.test(v) || 'Please enter a correct URL to your website'
],
I want to change the validation in the rule object to make it not required but if user entered a url it must be correct
This is how I manage to validate non required fields with Vuetify:
urlRules: [
(v) => ( !v || YOUR_REGEX.test(v) ) || 'Please enter a correct URL to your website'
],
Check the !v. I am validating first, that if nothing is passed, will trigger a true value, this means, will not be required. But if something is passed, will check your regex or whatever expression you want to place.
There are other options, like an if else inside the rules, but i prefer this (prettier).
You can do it like below
urlRules: [
v => (v && v.length > 0 && !YOUR_REGEXP.test(v)) ? 'Please enter a correct URL to your website' : true
],
I solved this by maintaining separate validation functions as follows:
export const emailFormat = v =>
/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(v) ||
"E-mail must be valid";
export const emptyEmailFormat = v => {
if (v && v.length > 0) {
return /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(v) ||
"E-mail must be valid";
} else {
return true
}
}
emailRules = {
isRequired: this.question.mandatory ? required : true,
emailFormat: this.question.mandatory ? emailFormat : emptyEmailFormat
};
I got this idea after posting this question
I used a regex that accept an empty value with the pattern I want
here is what I used
urlRules: [
v => /^$|[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi.test(v) || 'Please enter a correct URL to your website'
],
so if there is a better answer share it with me plz

How to filter by sub-object in Rally 2 SDK

I'm trying to query for user stories whose release start date is greater than a particular date. Is it possible to do this using the "filters" config rather than querying all stories and then checking manually?
Is this valid? :
Ext.create('Rally.data.WsapiDataStore', {
model: 'UserStory',
context: {
project: '/project/xxxx'
},
autoLoad: true,
fetch: ['Rank', 'FormattedID', 'Release'],
filters: [
{
property: 'Release.ReleaseStartDate',
operator: '>',
value: '2012-10-10'
}
]
});
It doesn't work, just fetches all records.
The code posted above does work. I was actually using a comboBox value in the "value" property. Turns out I didn't convert it to a proper DateTime format and hence the comparison was failing and returning all records.
In my case I had to use Rally.util.DateTime.toIsoString in order to compare the value in the combobox.