rickharrison/validate.js

How to write custom rules - globally

dvlden opened this issue · 1 comments

I am aware that we can do this:

const FORM = document.querySelector('#Form')

const FORM_VALIDATOR = new FormValidator(FORM, [{
    name: 'name',
    rules: 'required|callback_valid_name'
}, {
    name: 'email',
    rules: 'required|valid_email'
}, {
    name: 'subject',
    rules: 'required|callback_valid_select'
}, {
    name: 'message',
    rules: 'required|min_length[50]|max_length[500]'
}], (errors, event) => {
    console.log(errors)
})

FORM_VALIDATOR.registerCallback('valid_full_name', value => {
    return /\b\w+\b/g.test(value) >= 2
}).setMessage('valid_name', 'Please enter your full name.')

FORM_VALIDATOR.registerCallback('valid_select', value => {
    return value > 0
}).setMessage('valid_select', 'The %s field must be selected.')

But then again, if I have another FORM on same or different page, where I may need those rules just like the one that exists in plugin by default required; I may also use valid_full_name or valid_select on other forms.

So how do we define them globally and not as per instance?

There is no way to define them globally at the moment. However, you can easily write an abstraction yourself that will define the rules every time you want to use the validator.