programer.tips, another cool thing from @nghuuphuoc!

hexColor validator

Validate a hex color

Validators

Improve it on Github

Options

Option HTML attribute Type Description
message data-bv-hexcolor-message String The error message
When setting options via HTML attributes, remember to enable the validator by setting data-bv-hexcolor="true".
You don't need to do that when using HTML 5 type="color" attribute.

Examples

Basic example

<form id="colorForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-sm-3 control-label">Color</label>
        <div class="col-sm-3">
            <input type="text" class="form-control" name="color" />
        </div>
    </div>
</form>
$(document).ready(function() {
    $('#colorForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            color: {
                validators: {
                    hexColor: {
                        message: 'The color code is not valid'
                    }
                }
            }
        }
    });
});

Color picker example

The following form uses a Bootstrap Color Picker.

Pick a color
<!-- Required Bootstrap ColorPicker library -->
<link href="/vendor/bootstrap-colorpicker/css/bootstrap-colorpicker.min.css" rel="stylesheet" />
<script src="/vendor/bootstrap-colorpicker/js/bootstrap-colorpicker.min.js"></script>

<style type="text/css">
/* Adjust feedback icon position */
#colorPickerForm .colorPickerContainer .form-control-feedback {
    right: -15px;
}
</style>

<form id="colorPickerForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-sm-3 control-label">Color</label>
        <div class="col-sm-4 colorPickerContainer">
            <div class="input-group" id="colorPicker">
                <input type="text" class="form-control" name="color" />
                <span class="input-group-addon" style="color: #fff">Pick a color</span>
            </div>
        </div>
    </div>
</form>
$(document).ready(function() {
    $('#colorPickerForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            color: {
                validators: {
                    hexColor: {
                        message: 'The color code is not valid'
                    }
                }
            }
        }
    });

    $('#colorPicker')
        .colorpicker()
        .on('showPicker changeColor', function(e) {
            $('#colorPickerForm').bootstrapValidator('revalidateField', 'color');
        });
});

Related validators

The following validators might be useful to you: