How to use vee validate with textarea - javascript

In my form i want to add a textarea field with vee validation.
Unfortunately, i cannot get the field to mentioned by yup schema.
import { Form, Field, ErrorMessage, useFieldError } from "vee-validate"
import { string } from "yup"
import * as yup from "yup"
const schema = yup.object({
name: string().required("Mandatory field"),
description: string().required("Mandatory field"),
})
This is my form field (edit by last comment: i missed the "v-bind" but still not work)
<Field name="description" v-slot="{ description }">
<textarea v-bind="description" id="description" cols="30" rows="10" />
</Field>
The field is filled but the validation was not mentioned.
i followed an example here, but it not work.

Here's a full working example:
<template>
<Field v-slot="{ field, errors }" v-model="comment" name="comment" rules="required">
<textarea v-bind="field" name="comment"/>
<div v-if="errors[0]">{{errors[0]}}</div>
</Field>
</template>
<script lang="ts">
import { Field } from 'vee-validate';
import { defineRule } from 'vee-validate';
import { required } from '#vee-validate/rules';
export default {
components: { Field },
data() {
return {
comment:''
}
},
created() {
defineRule('required', required);
}
};
</script>
Things you were missing:
Rules ("required"), otherwise Vee Validate has nothing to do
v-slot errors - get the errors so you can show them
v-model on the Field (and a data element in your Vue component)

Related

Vue3 v-model remove spaces on input paste

Consider the following example Vue component:
Template:
<template>
<input
id="pin"
v-model="pin"
type="password"
name="pin"
placeholder="Pin"
#input="removeSpace($event.target)"
/>
</template>
Script:
<script>
import { ref } from 'vue'
const pin = ref('')
const removeSpace = (target) => {
pin.value = target.value.replace(/\s/g, '')
}
</script>
How would I go about moving the removeSpace function in this component to VueX4 store? So I can use it in multiple components? Can't seem to get it to work, the input field doesn't update.
I have tried something as follows:
Template:
<template>
<input
id="test"
v-model="store.state.testPin"
type="text"
name="test"
placeholder="test"
#input="store.dispatch('removeSpace', $event.target)"
/>
</template>
VueX store:
import { createStore } from 'vuex'
const store = createStore({
state: {
testPin: ''
},
actions: {
removeSpace(state, target) {
state.testPin = target.value.replace(/\s/g, '')
}
}
})
export default store

Vue 3: emit warning even though emits is present

I receive the following warning:
[Vue warn]: Extraneous non-emits event listeners (addData) were passed to component but could not be automatically inherited because component renders fragment or text root nodes. If the listener is intended to be a component custom event listener only, declare it using the "emits" option.
at <UserData onAddData=fn<bound dataSubmit> >
at <App>
in my Vue3 app. I use emits:["add-data"] in UserData.vue but the warning still appears.
Here are the relevant parts of the vue project:
app.vue
<template>
<div class="columns">
<div class="column">
<user-data #add-data="dataSubmit" />
</div>
<div class="column">
<active-user #delete-user="deleteUser" v-for="user in users" :key="user.id" :name="user.name" :age="user.age" :id="user.id" />
</div>
</div>
</template>
<script>
export default {
data() {
return {
users: []
}
},
methods: {
dataSubmit(name, age) {},
deleteUser(id) {}
}
}
</script>
UserData.vue
<template>
<h2>Add new user:</h2>
<form #submit.prevent="submitData">
<label>Name*</label>
<input type="text" v-model="name" placeholder="Name" />
<label>Age*</label>
<input type="text" v-model="age" placeholder="Age" />
<button>add</button>
</form>
</template>
<script>
export default {
emits: ["add-data"],
data() {
return {
name: "",
age: ""
}
},
methods: {
submitData() {
this.$emit("add-data", this.name, this.age)
}
}
}
</script>
main.js
import { createApp } from 'vue'
import UserData from './components/UserData.vue'
import ActiveUser from './components/ActiveUser.vue'
import App from './App.vue'
const app = createApp(App);
app.component("active-user", ActiveUser);
app.component("user-data", UserData);
app.mount('#app')
It works fine, but it just displays the warning.
If I change the emits part to emits: ["add-data", "addData"] the warning disappears.
There is an open bug for this:
https://github.com/vuejs/vue-next/issues/2540
For now you'll need to use emits: ['addData'] to avoid the warning.

Ember form-for addon's text-field onblur not working

Using the latest Ember Version 3.11
I tried onblur and focusOut, but focusOut throws error as it's a tagless component. None of them are working.
I'm trying to build a user form and validate the input when the user blur's from the field.
I'm using the below addon's together
https://github.com/martndemus/ember-form-for
https://github.com/poteto/ember-changeset
https://github.com/poteto/ember-changeset-validations
Component Template File
{{#form-for user submit=(action "submit") as |f|}}
{{f.text-field "name" autocomplete="off" placeholder="enter name" onblur=(action "validateOnBlur")}}
{{#if user.error.name}}
<p>{{user.error.name.validation}}</p>
{{/if}}
{{f.email-field "email"}}
{{#if user.error.email}}
<p>{{user.error.email.validation}}</p>
{{/if}}
{{f.password-field "password" }}
{{#if user.error.password}}
<p>{{user.error.password.validation}}</p>
{{/if}}
{{f.submit "Create User"}}
{{/form-for}}
Component Javascript File
import Component from '#ember/component';
import { get } from '#ember/object';
import Changeset from 'ember-changeset';
import lookupValidator from 'ember-changeset-validations';
import UserValidations from '../../validations/user';
export default Component.extend({
init() {
this._super(...arguments);
this.user = new Changeset(get(this, 'model'), lookupValidator(UserValidations), UserValidations);
},
actions:{
validateOnBlur(changeset, property){
debugger
},
async submit(changeset){
await changeset.validate();
if(changeset.isValid){
changeset.save();
}
}
}
});
Validator
import {
validatePresence,
validateLength,
validateFormat
} from 'ember-changeset-validations/validators';
export default {
name: validatePresence(true),
email: [
validatePresence(true),
validateFormat({ type: 'email' })
],
password: [
validatePresence(true),
validateLength({ min: 8 })
]
};
I found the cause why onblur is not getting triggered, as there is no attribute onblur in the text-field.hbs
https://github.com/martndemus/ember-form-for/blob/master/addon/templates/components/form-fields/text-field.hbs
The passed onblur from the form is not getting attached to it. I added onblur=onblur under f.control in the addon file(text-field.hbs) directly for checking and now it's working fine.

how to send the redux-form data

I have login component. Here I have used redux-form. As I am new to react, can you help to get the form data from redux-form (how to submit the form data)?
<form onSubmit={this.onSubmit}>
<div className="padding5">
<Field name="email" type="email" component={RenderField} label="Email Id" />
</div>
<div className="padding5">
<Field name="Password" type="Password" component={RenderField} label="Password" />
</div>
<div className='buttonSection'>
<button type="submit" disabled={this.state.errors} className='buttonField padding5'>Reset Password</button>
</div>
</form>
Your code looks fine.
You have to use Form from redux-form:
import { reduxForm, Form } from 'redux-form';
// Your form component
<Form onSubmit={this.onSubmit}>
// Your form
</Form>
Make sure you have add redux-form to your redux store:
import { combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form';
const combinedReducers = combineReducers({
form: formReducer
})
and you are exporting your form wrapped:
import { reduxForm, Form } from 'redux-form';
// Your form
export default reduxForm({
form: 'name-of-form'
})(MyForm);
First you should use Form component from redux-form
import { reduxForm, Form, Field } from 'redux-form';
Also when connected to redux-form your component receives a handleSubmit prop you should use in your onSubmit event listener so it should be :
<Form onSubmit={this.props.handleSubmit(this.onSubmit)} />
Then your submit button will do the job calling this.onSubmit with a collection of values with field names as keys :
onSubmit = values => {
console.log(values); // => { email: '', password: '' }
}

Redux form props & typescript

Was looking for years, didn't find anything worthy tho.
When I was working with flow, I could simply:
import { type FieldProps, FormProps } from 'redux-form';
Is there a similar (and that easy) way to properly set props to redux form in typescript?
Docs aren't saying anything about typescript, there's only a page for Flow typings.
However, I found that I can import something like propTypes from redux-form:
import { reduxForm, propTypes } from 'redux-form'
However - redux-form has nothing like propTypes exported, so docs are kinda deprecated.
Link: https://redux-form.com/7.2.1/docs/api/props.md/
Thanks in advance for any kind of help.
tl;dr class RegistrationForm extends React.PureComponent<any> {
what to drop here ^^^^^
You need to install the #types/redux-form package with your package manager. The #types/redux-form package includes types definitions for redux-form package.
Then you can import type definitions from redux-form, for example InjectedFormProps.
Your form that will be wrapped with reduxForm() should has props that extends InjectedFormProps<FormData = {}, P = {}>.
reduxForm() type is generic reduxForm<FormData = {}, P = {}>(...
See the example:
import * as React from 'react';
import { reduxForm, InjectedFormProps, Field } from 'redux-form';
import { IUser } from './index';
interface IProps {
message: string;
}
class UserForm extends React.Component<InjectedFormProps<IUser, IProps> & IProps> {
render() {
const { pristine, submitting, reset, handleSubmit, message } = this.props;
return (
<form onSubmit={handleSubmit}>
<div>{message}</div>
<div>
<label>First Name </label>
<Field
name="firstName"
component="input"
type="text"
placeholder="First Name"
/>
</div>
<div>
<label>Last Name </label>
<Field
name="lastName"
component="input"
type="text"
placeholder="Last Name"
/>
</div>
<div>
<button type="submit" disabled={pristine || submitting}>
Submit
</button>
<button type="button" disabled={pristine || submitting} onClick={reset}>
Clear Values
</button>
</div>
</form>
);
}
}
export default reduxForm<IUser, IProps>({
form: 'userForm',
})(UserForm);
The source code of #types/redux-form package is located here. You can see the types there and more complicated examples in the redux-form-tests.tsx file that is used for types checking.

Categories

Resources