Comparing two fields with vue-validator

11/23/2016 08:25:00 AM

I was looking for a simple way to compare two fields with vue.js without much JavaScript, and came up with the following HTML and JavaScript code.

We use 2 fields in total. The first field must contain an ID so we can look up the element using "document.getElementById" to find the field in our custom validator. The second field will contain our vue-validator attributes.

The JS code

    equals: function(val, event) {
        var element = this._el;
        var fieldIDToCompare = element.getAttribute('compareto');
        var elementToCompare = document.getElementById(fieldIDToCompare);

        if (elementToCompare && val === elementToCompare.value) {
            return true;
        } else {
            return false;

The HTML code

<input type="text" id="newPasswordEdit">  
<input type="text" compareto="newPasswordEdit" v-validate:newrepeatpassword="['equals']"> 

You can have a look on this fiddle here how it works: Click here

You Might Also Like

0 reacties