1000hz / bootstrap-validator

A user-friendly HTML5 form validation jQuery plugin for Bootstrap 3
http://1000hz.github.io/bootstrap-validator
MIT License
2.38k stars 1.07k forks source link

How to make custom function to validate data? #622

Open mrrtee opened 6 years ago

mrrtee commented 6 years ago

I'm using this validation script of 1000hz I have textbox to input data of Citizen ID which having algorithm to check accuracy of that data Basically, there are 13 digits of integer I have general JavaScript to check it, but I want to put it into 1000hz

This is that script

function checkID(id) { if (id.length != 13) { return false; } for (i=0, sum=0; i < 12; i++) { sum += parseFloat(id.charAt(i))*(13-i); } if ((11-sum%11)%10!=parseFloat(id.charAt(12))) { return false; } return true; }

How can I do?

pokemon4e commented 6 years ago

You can add custom validator by providing a function that receives a jQuery element as an argument and returns an error message if the field is invalid. Thus you should activate the validation via JavaScript:

$('#myForm').validator({
    custom: {
        'citizen': function ($el) {
            if (!checkID($el.val)) {
                return "Invalid Citizen Id."
            }
        }
    }
});

Adding the validator to an input is done just like the others, by referencing its name as a data attribute:

 <input data-citizen="" required>

Please refer to the documentation: http://1000hz.github.io/bootstrap-validator/