In the below example I was using VueJs in Laravel and needed to check that a form input followed the HH:MM:SS format using VeeValidate.
Note : VeeValidate already has a date format validator so if you are looking for that references their documentation here : http://vee-validate.logaretm.com/validation.html#rule-date_format
How to add custom HH:MM:SS validation using VeeValidate
HTML :
1 2 3 4 5 6 7 8 9 10 |
<div class="form-group"> <label class="col-md-1 control-label">From</label> <div class="col-md-5"> <div class="input-icon"> <i class="fa fa-clock-o time"></i> <input id="from-time" name="from-time" v-validate="'is_time|required'" type="text" class="form-control time" placeholder="00:00:00"> </div> <span v-show="errors.has('from-time')" class="text-danger">{{ errors.first('from-time') }}</span> </div> </div> |
Here we assign a custom validation type ‘is_time’ as well are making the field required. VeeValidate will then look for a matching ‘is_time’ rule in the validator. Below we extend the validator to add this rule.
VueJS :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<script> import VeeValidate from 'vee-validate'; Vue.use(VeeValidate); export default { ... created() { VeeValidate.Validator.extend('is_time', { getMessage: field => `The format must be HH:MM:SS`, validate: (value) => new Promise(resolve => { let regex = new RegExp("([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])"); resolve({ valid: value && regex.test(value) }); }) }); }, ... } </script> |
Thanks for reading – I hope this was helpful.