JSFiddle - React, Tailwind, and code Playground

by jmpp77

HTML

<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vuelidate.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/validators.min.js"></script>
<main id="app">

  <form action="" @submit.prevent="sendForm">
      <h3>Form sent {{ counter }} times!</h3>
  
      <input
         type="tel"
         id="telephone"
         v-model.lazy="phone"
         placeholder="06…"
         class="form-control input-block"
         :class="{ 'field-valid': $v.phone.$dirty && !$v.phone.$invalid, 'field-invalid': $v.phone.$dirty && $v.phone.$invalid }"
         @blur="$v.phone.$touch()"
      />
      
      <small v-if="$v.phone.$dirty && !$v.phone.required">Field is required</small>
      <small v-if="$v.phone.$dirty && !$v.phone.startWith0">Phone number must have 10 digits and start with "0"</small>
      <small v-if="$v.phone.$dirty && !$v.phone.$invalid">Seems good!</small>

      <button type="submit">Send form</button>
  </form>
  
  <pre>{{ JSON.stringify($v, null, 2) }}</pre>

</main>

CSS

html {
  font-family: sans-serif;
}

input {
  border: thin solid gray;
  padding: 0.2em 0.6em;
  border-radius: 0.15em;
}

.field-valid {
  border: thin solid green;
  color: green;
}

.field-invalid {
  border: thin solid red;
  color: red;
}

input + small {
  display: block;
  font-size: 0.8em;
}

input.field-valid + small { color: green; }
input.field-invalid + small { color: red; }

button[type='submit'] {
  display: block;
  margin-top: 1em;
}

JavaScript

Vue.use(window.vuelidate.default);

// Validators 
const required = validators.required; // vuelidate builtin
const startWith0 = validators.helpers.regex("startWith0", /^0[0-9]{9}$/); // custom regex (must start with "0" and have 10 digits)

new Vue({
  el: '#app',
    data() {
      return {
      	phone: '',
        counter: 0,
    	}
  	},
    methods: {
    	sendForm() {
      	this.$v.$touch();
        if (this.$v.$invalid) {
            return;
        }
        
        // Form has no errors, hurray! …
        this.counter++;
        
        // Let's reset for using it again!
      	this.$v.$reset();
        this.phone = '';
      }
    },
    validations: {
    	phone: { required, startWith0 }
    }
});