I use BootstrapValidator as my validation component. I need to give options which are gathered from PHP into its constructor like this:
PHP Code to generate fields:
$fields = "";
foreach ($form["questions"] as $key => $value) {
if (!empty($value["validators"])) {
$fields .= "\"" . $key . "\":" . json_encode($value["validators"]) . ",";
}
}
$new_fields = "{" . chop($fields, ",") . "}";
Javascript part is:
$('#my_form').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: <?php echo $new_fields; ?>
});
It prints something like that:
$('#fc_register_form').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
"field_1": {"notEmpty": {"message": "The ****** cannot be empty"}},
"field_1_confirm": {
"notEmpty": {"message": "The ******* must be same with first input for ******."},
"identical": {
"field": "field_1",
"message": "The given value is not same with first input for ****"}
},
"field_2": {"notEmpty": {"message": "The ******* empty"}},
"field_3": {"notEmpty": {"message": "The ******* empty"}},
"field_4": {"notEmpty": {"message": "The ****** is required and cannot be left empty"}}
}
});
So, may double quotes cause it not to work? Or what is wrong with that? It should not be that much though, i guess...
Yeap, i figured it out what i was doing wrong.
It is not about how i encoded my array $fields
, it is about missing a child validators
which is required by bootstrapValidator.
I just changed this:
........
$fields[$key] = $value["validators"];
........
into this:
........
$fields[$key]["validators"] = $value["validators"];
........
And it converts my entire object to what bootstrapValidator required. Also thanks for owner of bootstrapValidator to make me aware of that I missed the validators
key.
Here is the complete library link: https://github.com/nghuuphuoc/bootstrapvalidator
Hope you guys find it useful.