0

我需要一个 jquery 函数来验证我的文本框值。

要求:必填字段:true,最小长度:8,最大长度:16,应仅允许字母、数字。

我写了一个函数:

jQuery.validator.addMethod("nameRegex", function (value) {
      //  alert(value);
        if (value.length >= 8) {
           // alert(value.length); 
                return value.match(/^[a-zA-Z0-9 ]+$/.test(value)); 
        }
    }, "Contain only letters, numbers."); 

但这不起作用,任何人都可以帮助我。

-辛杜.A

4

1 回答 1

0

Hiya hope this help :)) Working Demo : http://jsfiddle.net/2FByp/2/

Like @zerkms said please be very clear what is not working. you can always refer to the validation plugin documentation && this might help you as well: using the jquery validation plugin, how can I add a regex validation on a textbox?

NOTE Please make sure all the rules are added correctly and compare your implementation with the jsfiddle above, else flick me jsfiddle I might be help BUT this js fiddle will help you to find out why it is not working. :)

HTML

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>

<script type="text/javascript">

</script>

<form method="post" id="myForm">

    Name regex (alphanumeric):<input type="text" name="name" />  
    <input type="submit" value="Go" />  
</form>​

JQuery Code

  $(function() {

    $.validator.addMethod("nameRegex", function(value, element) {
        return this.optional(element) || /^[a-z0-9\-]+$/i.test(value);
    }, "Username must contain only letters, numbers, or dashes.");

    $("#myForm").validate({
        rules: {
            "name": {
                required: true,
                nameRegex: true,
                minlength: 8

            }
        },
        messages: {
            "name": {
                required: "You must enter a login name",
                nameRegex: "Contain only letters, numbers."
            }
        }
    });

});​

Hope this is helpful cheers!

于 2012-04-05T06:08:30.760 回答