I got an input field, which I want to be live validated. As its only one single field, I would like to avoid using a whole library for vue form validations.
There are three things I would like to accomplish:
- The input field is valid, if there is a first name, a space and a last name. For example
a c
is valid, whilea
is not. Althougha b c
is valid. - The input field is wrapped inside a #wrapper, which should use
valid
orinvalid
, depending on the validation - If the user tries to send a invalid string (by clicking the button or pressing enter) the
.alert
should show.
I have tried to write a vue script:
computed: {
inputClass: function () {
var inputField=document.getElementById("inputField").value;
if (inputField==null || inputField=="") {
return 'invalid';
} else {
return 'valid';
}
}
}
Sadly, this script always returns 'valid', even when the input field is empty.
As I am using vue.js for some other reasons, it seems a good idea to implement this inside my vue app. But I could although use jQuery. I have tried to solve the third need of my list with the following script:
$('button').on('click', function(){
if( $(this).val().length === 0 ) {
$('.alert').fadeIn();
} else {
$('.alert').hide();
}
});
To make it easier to understand I have created a JS Bin with the HTML markup and code.