I want to display an additional input if the person clicks yes and clicks on nothing
i try to do that with v-if but i the value never change
this is the entire page in vuejs maybe i need to do a method, i already try without quote and with, i to set value like club = 1 but didn't work to.
I'm not sure if my v-bind is good too
<el-form-item label="Possédez vous un club ?">
<el-radio-group v-model="ruleForm.club">
<el-radio label="Oui" v-bind:value="true"></el-radio>
<el-radio label="Non" v-bind:value="false"></el-radio>
</el-radio-group>
</el-form-item>
<el-form-item v-if="'ruleForm.club' == true" label="Nom du club" prop="nClub">
<el-input v-model="ruleForm.nClub" autocomplete="off"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" #click="submitForm('ruleForm')">Submit</el-button>
<el-button #click="resetForm('ruleForm')">Reset</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
data () {
var validatePseudo = (rule, value, callback) => {
if (value === '' || value !== 'coach') {
callback(new Error('Please input the pseudo'))
} else {
callback()
}
}
var validatePass = (rule, value, callback) => {
if (value === '' || value !== 'password') {
callback(new Error('Please input the password'))
} else {
callback()
}
}
return {
ruleForm: {
nom: '',
prenom: '',
pseudo: '',
email: '',
pass: '',
statue: '',
club: '',
nClub: ''
},
rules: {
pseudo: [
{ validator: validatePseudo, trigger: 'blur' }
],
pass: [
{ validator: validatePass, trigger: 'blur' }
]
}
}
},
methods: {
submitForm (formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
this.$router.push({
name: '/'
})
} else {
console.log('error submit!!')
return false
}
})
},
resetForm (formName) {
this.$refs[formName].resetFields()
},
}
}
</script>
I do not really understand your question, but from what I can tell you would like to add an inputfield if a user selects a certain radio button using v-if. I've recreated this in a jsfiddle. Is this wat your looking for?
Link: https://jsfiddle.net/Mertakus/8wx4h7up/3/
Related
I have a radio button that when I click it calls a function with two parameters in the function (value and step), and when I make a test with testing librairy I would like that when I simulate the click of the button I return the two parameters.
Button
<Form.Check
inline
label={'form.email'}
name="media"
value={`LETTER`}
type="radio"
data-testid="EMAIL"
onClick={(e) => {
const target = e.target as HTMLTextAreaElement;
changeMedia(target.value, data);
}}
/>
Function ChangeMedia
const changeMedia = (value: any, step: any) => {
step.definition?.steps
.filter((obj: any) => obj.media.includes(value))
.map((item: any) => {
if (value === 'EMAIL') {
item.media = 'LETTER';
return item;
} else if (value === 'LETTER') {
item.media = 'EMAIL';
return item;
}
return item;
});
return data;
};
Objet Step
const step = {
definition: {
steps: [
{
document_model: 'template_circularization',
email_model: 'email_circularization',
label: {
EN: 'Circularization',
FR: 'Circularisation',
},
media: 'LETTER',
name: 'mail_circularization',
onDemandOnly: true,
},
],
},
};
Test
const radio = screen.getByTestId('EMAIL');
fireEvent.click(radio, { target: { value: 'EMAIL, step: step } });
when I do a console.log of value and step I get this :
value EMAIL
step {}
what would be the solution to retrieve the step object via firevent.click ?
I have a form page and I use it for both create and update
My form fields are like this;
myForm: {
name: (...)
email: (...)
password: (...)
}
I can successfully submit a request.
When we come to the update process, I get the data in this way (this.myForm = response.data)
When I send an update request I just want the form fields to go but it goes like this
myForm: {
name: (...)
email: (...)
password: (...)
createdAt: (...)
updatedAt: (...)
_id: (...)
}
I don't want to send createdAt, updatedAt, _id fields
How can I submit only form fields in Vue.js or Element-ui? (I am using element-ui btw)
Is there something like this.$refs.myForm.fields or this.$refs.myForm.values I couldn't find it
My code: Code picture
<template>
<div class="app-container">
<el-form ref="myForm" label-position="top" :model="myForm">
<el-form-item>
<label>Name</label>
<el-input v-model="myForm.name" />
</el-form-item>
<el-form-item>
<label>Email</label>
<el-input v-model="myForm.email" />
</el-form-item>
<el-form-item>
<label>Password</label>
<el-input v-model="myForm.password" />
</el-form-item>
<el-button type="primary" #click="submitForm('myForm')">Kaydet</el-button>
</el-form>
</div>
</template>
<script>
export default {
name: 'UserForm',
data() {
return {
myForm: {
name: '',
email: '',
password: ''
}
}
},
created() {
if (this.$route.params.id) {
this.getFormData(this.$route.params.id)
}
},
methods: {
submitForm() {
if (!this.$route.params.id) {
this.$store.dispatch('user/create', this.myForm)
} else {
this.$store.dispatch('user/update/', this.myForm)
}
},
getFormData(id) {
this.$store.dispatch('user/get', id).then((response) => {
this.myForm = response.data
})
}
}
}
</script>
Instead of posting the entire 'this.myForm', just specify the fields you want to post in a new object.
submitForm() {
if (!this.$route.params.id) {
this.$store.dispatch('user/create', this.myForm)
} else {
this.$store.dispatch('user/update/', {
name: this.myForm.name,
email: this.myForm.email,
password: this.myForm.password
})
}
}
UPDATE: Following comments from OP, if you're expecting more that 'name', 'email', and 'password', you can just delete the properties you don't want to send.
submitForm() {
if (!this.$route.params.id) {
this.$store.dispatch('user/create', this.myForm)
} else {
delete this.myForm.createdAt,
delete this.myForm.updatedAt,
delete this.myForm._id
this.$store.dispatch('user/update/', this.myForm)
}
}
I started to study React and wanted to create the form for multiple inputs, where I can check the validation of the data at the time of input and again before submitting of the form.
The conditions to submit: all fields are mandatory and the data is valid.
Currently, if user enters invalid data in input field, error text is displayed near the same field. And if user clicked button "submit" on the form with empty fields, error text is also displayed.
But I can't really work it out, how should I do the validation before the submission of the form in my example: : the form has the input field with an error or not.
import React from 'react'
import { render } from 'react-dom'
const ErrorOutput = props => {
let name = props.name
let inputValue = props.case
let submit = props.submit
console.log(props.submit)
if (name === 'firstName') {
if (!inputValue.match(/^[a-zA-Z]+$/) && inputValue.length > 0) {
return <span>Letters only</span>
} else if (submit && inputValue.length === 0) {
return <span>Required</span>
}
return <span></span>
}
if (name === 'telNo') {
if(!inputValue.match(/^[0-9]+$/) && inputValue.length > 0) {
return <span>Numbers only</span>
} else if (submit && inputValue.length === 0) {
return <span>Required</span>
}
return <span></span>
}
}
class App extends React.Component {
constructor(props){
super(props)
this.state = {
firstName: '',
telNo: '',
submit: false
}
}
handleSubmit(e){
e.preventDefault()
let submit = true
this.setState ({submit: submit})
// ... Validation
}
handleValidation(e) {
this.setState({
[e.target.name]: e.target.value
})
}
render() {
return (
<form onSubmit={this.handleSubmit.bind(this)}>
<div>
<label>
First name:
</label>
<input
type='text'
name ='firstName'
value = {this.state.firstName}
onChange = {this.handleValidation.bind(this)}
/>
<ErrorOutput case={this.state.firstName} name={'firstName'} submit = {this.state.submit} />
</div>
<div>
<label>
Phone number:
</label>
<input
type='tel'
name ='telNo'
value = {this.state.telNo}
onChange = {this.handleValidation.bind(this)}
/>
<ErrorOutput case={this.state.telNo} name={'telNo'} submit = {this.state.submit} />
</div>
<button>
Submit
</button>
</form>
)
}
}
render(
<App />,
document.getElementById('root')
)
the following code is an example of adding data via form and form validation prior to the submit. More validations can be added.
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
age: '',
email: '',
errorName: '',
errorAge: '',
errroMail: '',
dataValue: false
};
this.getName = this.getName.bind(this);
this.getAge = this.getAge.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.postDatainDisplay = this.postDatainDisplay.bind(this);
}
componentWillReceiveProps(nextProps) {
if (this.props.name !== nextProps.name) {
this.setState({ dataValue: true });
}
}
postDatainDisplay(dataObj) {
this.props.postData(dataObj);
}
getName(event) {
const { name, age } = this.state;
this.setState({ errorName: '' });
this.setState({ name: event });
}
getAge(event) {
const { age } = this.state;
this.setState({ errorAge: '' });
this.setState({ age: event });
}
handleSubmit() {
const { name, age } = this.state;
//add more validation here
if (name === '') {
this.setState({ errorName: 'name cannot be blank', dataValue: false
});
} else if (age === '') {
this.setState({ errorAge: 'Age cannot be blank', dataValue: false });
} else
{ this.setState({ data: { name, age } }, () => {
this.props.sendData(this.state.data);
}
render() {
const { name, age } = this.props;
return (
<div className="container">
<form>
name:<input
type="text"
onChange={event => {
this.getName(event.target.value);
}}
/>
{this.state.errorName}
<br />
<br />
age:{' '}
<input
type="text"
onChange={event => {
this.getAge(event.target.value);
}}
/>
{this.state.errorAge}
<br />
<br />
<input type="button" onClick={this.handleSubmit} value="Submit"
/>
</form>
</div>
class App extends React.Component {
constructor(props){
super(props)
this.state = {
form:{
firstName: {
value: '',
validation: {
required: true
},
valid: false,
touched: false
},
telNo: {
value: '',
validation: {
required: true
},
valid: false,
touched: false
}
},
formIsValid:false
}
}
checkValidity(value, rules) {
let isValid = true;
if (rules.required) {
isValid = value.trim() !== '' && isValid;
}
return isValid;
}
handleValidation = (event) => {
let fieldName = event.target.name;
let fieldValue = event.target.value;
const updatedCategoryForm = {
...this.state.form
};
const updatedFormElement = {
...updatedCategoryForm[fieldName]
};
updatedFormElement.touched = true;
updatedFormElement.value = fieldValue;
updatedFormElement.valid = this.checkValidity(updatedFormElement.value, updatedFormElement.validation);
if (!updatedFormElement.valid && updatedFormElement.validation ) {
updatedFormElement.elementValidation = "Invalid";
} else {
updatedFormElement.elementValidation = "";
}
updatedCategoryForm[fieldName] = updatedFormElement;
let formIsValid = true;
for (let inputIdentifier in updatedCategoryForm) {
formIsValid = updatedCategoryForm[inputIdentifier].valid && formIsValid;
}
this.setState({ form: updatedCategoryForm, formIsValid: true });
}
Based on the value of formIsValid field disable submit button
I am using formik (https://github.com/jaredpalmer/formik) for forms of my react application.
I want to be able to update component state to show a success message after handleSubmit completed successfully.
But I am unable to achieve that. I am getting errors.
export default withFormik({
mapPropsToValues ({ email }) {
return {
email: email || ''
};
},
validationSchema: Yup.object().shape({
email: Yup.string().email('Email not valid').required('Email is required')
}),
handleSubmit(values, { resetForm, setErrors, setSubmitting }) {
Accounts.forgotPassword({
email: values.email
}, (error) => {
if (error) {
setErrors({ email: 'Error: ' + error.reason });
} else {
this.setState({success: 'Success: Check your inbox for a reset link!'});
resetForm();
}
setSubmitting(false);
});
}
})(RecoverPassword);
We can't access to wrapped component from a higher order component.
There is no way to access a wrapped component's state from a higher-order component. Formik has a built-in errors and status handling setters and getters.
export default withFormik({
mapPropsToValues ({ email }) {
return {
email: email || ''
};
},
validationSchema: Yup.object().shape({
email: Yup.string().email('Email not valid').required('Email is required')
}),
handleSubmit(values, { resetForm, setErrors, setSubmitting, setStatus }) {
Accounts.forgotPassword({
email: values.email
}, (error) => {
if (error) {
setErrors({ email: 'Error: ' + error.reason });
} else {
resetForm();
setStatus('Check your inbox for a reset link.');
// setStatus is part of the "formik bag".
}
setSubmitting(false);
});
}
})(RecoverPassword);
Is there a cleaner way to define unique form field in extjs. Below is a sample code that is checking on client UID on client creation/edition. This code is working but has some bugs - for example on client creation if you enter a value that is already present in DB validator returns true until you unfocus the field.
Ext.define('AM.view.client.UniqueField', {
extend: 'Ext.form.field.Text',
alias : 'widget.uniquefield',
vtype: 'UniqueUid',
initComponent: function() {
Ext.apply(Ext.form.field.VTypes, {
UniqueUidMask : /[0-9]/i,
UniqueUid : function(val,field) {
if (val.length < 9) {
Ext.apply(Ext.form.field.VTypes, {
UniqueUidText: 'Company ID is too small'
});
return false;
} else {
var paste=/^[0-9_]+$/;
if (!paste.test(val)) {
Ext.apply(Ext.form.field.VTypes, {
UniqueUidText: 'Ivalid characters'
});
return false;
} else {
var mask = new Ext.LoadMask(field.up('form'),{msg:'Please wait checking....'});
mask.show();
var test= 0;
var store = Ext.create('AM.store.Clients');
store.load({params:{'uid':val, 'id': Ext.getCmp('client_id').getValue()}});
store.on('load', function(test) {
mask.hide();
if(parseInt(store.getTotalCount())==0){
this.uniqueStore(true);
}else{
Ext.apply(Ext.form.field.VTypes, {
UniqueUidText: 'Company ID is already present'
});
this.uniqueStore(false);
}
},this)
return true;
}
}}
},this);
this.callParent(arguments);
},
uniqueStore: function(is_error){
Ext.apply(Ext.form.field.VTypes, {
UniqueUidMask : /[0-9]/i,
UniqueUid : function(val,field) {
if (val.length < 9) {
Ext.apply(Ext.form.field.VTypes, {
UniqueUidText: 'Company ID is too small'
});
return false;
} else {
var paste=/^[0-9_]+$/;
if (!paste.test(val)) {
Ext.apply(Ext.form.field.VTypes, {
UniqueUidText: 'Ivalid characters'
});
return false;
} else {
var mask = new Ext.LoadMask(field.up('form'),{msg:'Please wait checking....'});
mask.show();
var store = Ext.create('AM.store.Clients');
store.load({params:{'uid':val, 'id': Ext.getCmp('client_id').getValue()}});
store.on('load', function(test) {
mask.hide();
if(parseInt(store.getTotalCount())==0){
this.uniqueStore(true);
}else{
this.uniqueStore(false);
}
},this)
return is_error;
}
}}
},this);
}
});
How about using server side validation?
I answered to similar issue here: extjs4 rails 3 model validation for uniqueness
Obviously you can change it to use "ajax" instead of "rest" proxy.