Custom jQuery Validator

12/17/2015 3:55:22 PM

The following will allow you to programmatically set validation on a forms input fields and include a custom validator. This example uses a validator to ensure that the number entered is > 0.

<form id="frmGreaterThanZero">
    <div>Favorite Number: <input type="text" name="favoriteNumber" /></div>
    <input type="submit" value="Greater Than Zero?" />
</form>

<script type="text/javascript">

    $(document).ready()
    {
        $('#frmGreaterThanZero').validate(
        {
            rules:
                {
                    favoriteNumber:
                        {
                            validator__greater_than_zero: true
                        }
                }
        });


        jQuery.validator.addMethod('validator__greater_than_zero', function (value)
        {
            //console.log("validating numeric value");
            return (value > 0);
        },
        "number > 0 required");
    };
</script>