C
C
coderisimo2017-07-20 07:55:27
JavaScript
coderisimo, 2017-07-20 07:55:27

Server-side validation of each form field using Vue. Optimal solution?

There are 15 fields. When changing each, you need to send a validation request to the server. I am using Vue. I'm thinking of creating computed fields according to the number of validated fields. Maybe there is a more elegant way?
For example, in jQuery, I would write one function that would take everything that is needed from the attribute of the validated field and, after receiving a response from the server, would change the type of the validated field depending on the validation results. And with Vue .... Doing 15 computed fields is somehow not so hot at all (((
Thanks.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
RaulDuke, 2017-07-20
@coderisimo

Think towards a generic input component.
Something like this:

<template>

    <input type="text"
      :placeholder="placeholder"
      :value="value"
      @input="onchange">
    <app-transition type="toggleDown">
      <div>{{ notify }}</div>
    </app-transition>
</template>

<script>
  export default {
    name: 'app-input',
    props: ['type', 'value', 'placeholder'],
    computed: {
      notify() {
        let text = 'Поле может содержать только ';
        return ( this.type === 'tel' &&  text + 'цифры' )
            || ( this.type === 'page' && text + 'латинские буквы, цифры (не менее 6 символов)' )
            || ( this.type === 'name' && text + 'русские и латинские буквы, цифры (не менее 3 символов)' )
      },
      validation(value) {
        return {
          tel: (/^[0-9]+$/).test(this.value) || !this.value.length,
          page: (/^[a-z0-9]+$/i).test(this.value) && this.value.length > 5,
          name: (/^[a-zа-яA-ZА-Я0-9 ]+$/i).test(this.value) && this.value.length > 3
        }
      }
    },
    methods: {
      onchange(e) {
        if ( this.validation[this.type] ) {
          this.$emit('input', e.target.value);
        }
      }
    }
  }
</script>

A
Artem0071, 2017-07-20
@Artem0071

There is a watch method
Just watch the form as a whole with it

E
Evgeny Kulakov, 2017-07-20
@kulakoff Vue.js

If you need to send data to the server for each change in the field, then I would also look towards a separate component field that can work with the server. In the component to change the field, send data to the server via debounce, catch the response and process it as needed in the component, showing errors, etc.
So you can then insert this component anywhere, specifying the address where to send data from this field as an input parameter.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question