使用jQuery进行Textarea验证

时间:2016-07-04 10:08:27

标签: javascript jquery jquery-validate textarea

我希望只将字母输入到文本区域中 它适用于输入字段,无法验证textarea是否可以使用jquery验证?或者另一种选择 2)将阻止恶意代码输入(如xss.js)

      <form action="" method="POST" enctype="multipart/form-data" name="messageForm">
  <p>name of sender: 
   <input class="input" name="sender" id="sender" value="" size="13"
     maxlength="13" dir="ltr" autocomplete="on" type="text" height="20" minlength="3" required><br>
   <p>name of receiver: 
      <input class="input" name="receiver" id="receiver" value="" size="13"
     maxlength="13" dir="ltr" autocomplete="on" type="text" height="20" minlength="3" required><br>
   <p>Message: <br>
     <textarea name="message" id="message"  type="text" value="" rows="5" cols="30" dir="ltr" required></textarea><br>
   <input value="Submit" name="button" alt="submit" onsubmit="" border="0" type="submit" align="absmiddle"></p>

 </form>
<script>
    $("#messageForm").validate();
</script>

的javascript

$().ready(function () {

    $("#submit").validate({
    rules: {
        sender: {
            required: true,
            minlength: 3,
          lettersonly: true
        },
        receiver: {
            required: true,
            minlength: 3,
            lettersonly: true
        },
        message: {
          required: true,
          minlength: 5,
          maxlength: 30,
          lettersonly: true
        },
      },
     messages: {
                sender: {required:"Please enter your name"},
                receiver:{required: "Please enter receiver name up to 3 characters"},
                message: {required: "Enter your message 3-20 characters"},
          },
 });

});

在Chrome上运行时会在最后一部分上显示错误:意外的标识符

1 个答案:

答案 0 :(得分:2)

您正在呼叫.validate()两次......

下面...

<script>
    $("#messageForm").validate();
</script>

在这里......

$().ready(function () {
    $("#submit").validate({...

.validate()方法仅用于初始化form上的插件,无法调用两次。始终忽略所有后续调用。

但是,在您的情况下,它会被忽略,因为您已将.validate()的第二个实例附加到$("#submit"),其中您的表单id不是submit而您的{ {1}}甚至没有form。您只能将id方法附加到您要验证的.validate(),即form

你只需要这个......

name="messageForm"

正如评论中所述,不再推荐$(document).ready(function () { $("[name='messageForm']").validate({ rules: { sender: { required: true, minlength: 3, lettersonly: true ... 。请改用$().ready(function () {...

DEMO:jsfiddle.net/unapufhp/