ariel
ariel

Reputation: 16140

Input validation: change default error message

If I do this on vue:

<input pattern="\d+">

It gets properly validated, but I get a popup with a message "Please match the requested format".

Is there any way to change this message? I can't find the documentation on the accepted validation tags.

JSFiddle: http://jsfiddle.net/ovz5p3wt/

Upvotes: 3

Views: 2492

Answers (1)

Daniel
Daniel

Reputation: 35724

so, as noted in comments, the way to do it is to use oninvalid and setCustomValidity

<input pattern="\d+" oninvalid="setCustomValidity('please use a number')">

However, if you want to do it using a script (since you are tagging at as vue) here is another solution that allows you to dynamically change the value you can use the script version. unfortunately @oninvalid doesn't seem to be supported by vue, so you'd need to set the functionality using $refs

updateCustomValidity(lang){
    var el = this.$refs.el;
    el.oninvalid = el.setCustomValidity(this[lang].message);
}

new Vue({
  el: "#app",
  data() {
  	return {
    	lang: 'en',
    	en: {
      	message: 'nope, sorry',
      },
      fr: {
      	message: 'sacre bleu'
      }
    }
  },
  watch: {
    lang: {
      handler(lang) {
        this.updateCustomValidity(lang);
      }
    }
  },
  methods: {
  	updateCustomValidity(lang){
        var el = this.$refs.el;
        el.oninvalid = el.setCustomValidity(this[lang].message);
    }
  },
  mounted() {
  	this.updateCustomValidity(this.lang);
  }
})
body { background: #20262E; padding: 20px; font-family: Helvetica;}
#app { background: #fff; border-radius: 4px; padding: 20px; transition: all 0.2s;}
input { margin: 8px 0;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>

<div id="app">
  EN: <input type="radio" v-model="lang" value="en">
  FR: <input type="radio" v-model="lang" value="fr">
  <form>
    <input pattern="\d+" value="text" ref="el">
    <button type="submit">Submit</button>
  </form>
</div>

Upvotes: 5

Related Questions