A
A
Aleksandr2017-08-16 19:04:11
JavaScript
Aleksandr, 2017-08-16 19:04:11

Field validation in VueJs?

There are a number of inputs:

<div class="form-group">
 	<label class="ui-label">Идентификатор банка</label>
  <el-input v-model="id" @focus="focus" @change="change('id', $event)">ID</el-input>
 </div>
<div class="form-group">
  <label class="ui-label">БИК банка</label>
  <el-input :class="{'ERROR': !isBicValid, 'OK': isBicValid}" v-model="bank_bic" @focus="focus" @change="change('bank_bic', $event)">БИК банка</el-input>
</div>
<div class="form-group">
  <label class="ui-label">Название банка</label>
  <el-input v-model="bank_name" @focus="focus" @change="change('bank_name', $event)">Название банка</el-input>
</div>	
<div class="form-group">
  <label class="ui-label">Корреспонденский счет банка</label>
  <el-input v-model="bank_corr_account" @focus="focus" @change="change('bank_corr_account', $event)">Кор. счет банка</el-input>
</div>

I started doing validation and several questions immediately appeared:
1) how best to write computedto validate all fields at once and is it generally possible to do this?
so far made for one
computed: {
  isBicValid() {
        return /^[0-9]{9}$/.test(this.bank_bic);
    }
},

2) how to correctly write a condition for the class, so that if the field is not empty, the ERROR class is not added
now, and for obvious reasons, ERROR is added, how to fix it?
:class="{'ERROR': !isBicValid, 'OK': isBicValid}"

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Evgeny Kulakov, 2017-08-16
@Sashjkeee

1. There are ready-made libs, for example: https://github.com/monterail/vuelidate
2. You can wrap the input in your custom component, into which you will pass the validation function
In the second question, as an option:

computed: {
  isBicValid() {
        return this.bank_bic.length > 0 ? /^[0-9]{9}$/.test(this.bank_bic) : true
    }
},

I
Igor, 2017-08-16
@hurgadan

the computed property isBicValid is a function. Write whatever you like in it, do whatever checks you like, and return true or false based on their result of the checks. In your example, you check only bank_bic, but nothing prevents you from checking the rest of the fields in the same place and only then executing return.

P
planc, 2017-08-16
@planc

https://laracasts.com/series/learn-vue-2-step-by-s...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question