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 に答える