4

我有一个 JS 代码,它的功能是验证表单,现在我要做的是添加 1 个函数来防止文本框用户名中的空格以及消息,“不允许空格”。到目前为止,这是我的 JS 代码:

$().ready(function()
    {
        $("#signupForm").validate(
        {
            rules:
            {
                full_name: "required",
                username: {
                    required: true,
                    minlength: 2
                },
                password: {
                    required: true,
                    minlength: 5
                },
                email: {
                    required: true,
                    email: true
                },
            },
            messages:
            {
                full_name: "Please enter your full name",
                username:
                {
                    required: "Please enter a username",
                    minlength: "Your username must consist of at least 2 characters"
                },

                password:
                {
                    required: "Please provide a password",
                    minlength: "Your password must be at least 5 characters long"
                },

                email: "Please enter a valid email address"
            }
        });
    });

任何人都可以给我的想法?谢谢。

4

3 回答 3

6

试试这个


添加一个名为 noSpace 的方法

jQuery.validator.addMethod("noSpace", function(value, element) {
    return !value.match(/\s/g);
}, "Spaces are not allowed");

将其设置为用户名的规则

rules: {
    // ...
    username: {
        // ...
        noSpace: true,
        // ...
    },
    // ...

如果要覆盖默认消息,请设置自定义消息

messages: {
    // ...
    username: {
        // ...
        noSpace: "Username should not contain spaces",
        // ...
    },
于 2012-09-24T07:41:33.533 回答
4
<script type="text/javascript">
function nospaces(t) {
    if(t.value.match(/\s/g)) {
        alert('Sorry, you are not allowed to enter any spaces');
    }
}
</script>

将以下属性添加到文本输入框

onkeyup="nospaces(this)"
于 2012-09-24T07:37:13.807 回答
1
jQuery.validator.addMethod("noSpace", function(value, element) { 
    return value.indexOf(" ") < 0 && value != ""; 
}, "No space allowed");

$("#signupForm").validate({
    rules: {
        username:
           {
              required: "Please enter a username",
              minlength: "Your username must consist of at least 2 characters",
              noSpace: true
           }
     }
});
于 2012-09-24T07:45:18.087 回答