【问题标题】:Form validation using Jquery plugin and additional methods使用 Jquery 插件和其他方法进行表单验证
【发布时间】:2019-06-21 06:42:13
【问题描述】:

我想使用 jquery 插件来验证我的表单,只在名称部分使用字母。这样当用户输入特殊字符或数字时就会出错。我还想在用户输入信息时检查表单验证,即在提交表单之前进行实时验证。

//jquery validation
	
	// Wait for the DOM to be ready
$(function() {
  // Initialize form validation on the registration form.
  // It has the name attribute "registration"
  $("form[name='book']").validate({
    // Specify validation rules
    rules: {
      // The key name on the left side is the name attribute
      // of an input field. Validation rules are defined
      // on the right side
      fname: {
        required: true,
        lettersonly: true
        },
      lname:{
        required: true,
        lettersonly: true
        },
      email: {
        required: true,
        // Specify that email should be validated
        // by the built-in "email" rule
        email: true
      },
     
    // Specify validation error messages
    messages: {
      fname: {
      required:"Please enter your firstname",
      lettersonly:"Letters allowed only"
      },
      lname: {
      required:"Please enter your firstname",
      lettersonly:"Letters allowed only"
      },
     
      email: "Please enter a valid email address"
    },
    // Make sure the form is submitted to the destination defined
    // in the "action" attribute of the form when valid
    submitHandler: function(form) {
      form.submit();
    }
  });
});
<script src="design/bootstrap-3.3.7-dist/js/jquery.validate.js"></script>
<script src="design/bootstrap-3.3.7-dist/js/additional-methods.js"></script>

<form name="book" id="book" action="" method="post">

    <div class="row form-group">
        <div class="col-md-6 ">
            <label class="" for="fname">First Name</label>
            <input type="text" name="fname" id="fname" class="form-control" placeholder="First Name">
        </div>
        <div class="col-md-6">
            <label class="" for="lname">Last Name</label>
            <input type="text" name="lname" id="lname" class="form-control" placeholder="Last Name">
        </div>
    </div>

    <div class="row form-group">
        <div class="col-md-6 ">
            <label class="" for="date">Date</label>
            <input type="text" id="date" class="form-control datepicker px-2" placeholder="Date of visit">
        </div>
        <div class="col-md-6">
            <label class="" for="email">Email</label>
            <input type="email" name="email" id="email" class="form-control" placeholder="Email">
        </div>
    </div>

    <div class="row form-group">
        <div class="col-md-12">
            <label class="" for="treatment">Service You Want</label>
            <select name="treatment" id="treatment" class="form-control">
                <option value="">Hair Cut</option>
                <option value="">Hair Coloring</option>
                <option value="">Perms and Curls</option>
                <option value="">Hair Conditioning</option>
                <option value="">Manicure</option>
                <option value="">Pedicure</option>
                <option value="">Nails Extension</option>
                <option value="">Nail Design</option>
                <option value="">Waxing Eyebrows</option>
                <option value="">Waxing Hands/Legs</option>
                <option value="">Full Face Waxing</option>
                <option value="">Full Body/Body Parts Wax</option>
            </select>
        </div>
    </div>

    <div class="row form-group">
        <div class="col-md-12">
            <label class="" for="note">Notes</label>
            <textarea name="note" id="note" cols="30" rows="5" class="form-control" placeholder="Write your notes or questions here..."></textarea>
        </div>
    </div>

    <div class="row form-group">
        <div class="col-md-12">
            <center><input type="submit" value="Book Now" class="btn btn-primary btn-lg"></center>
        </div>
    </div>

</form>

我想使用 jquery 插件来验证我的表单,只在名称部分使用字母。这样当用户输入特殊字符或数字时会出错

【问题讨论】:

    标签: javascript jquery html forms validation


    【解决方案1】:
          var RegEx = /^[a-zA-Z\s]*$/; 
    
          if (RegEx.test($('#input').val())) {
    
          } 
          else {
              $('#input').val("");
          }
    });​````
    
    You have to wrap all the input elements in <form></form> and use jquery Validate plugin. Refer this link: http://jqueryvalidation.org/validate/ for detailed explanation
    

    【讨论】:

      【解决方案2】:

      做这样的事情怎么样?

      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>JS Bin</title>
      </head>
      <body>
      <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
      
        <form id="form">
          <label for="name">Name: </label>
          <input type="text" name="name">
          <div id="error"></div>
        </form>
      
      <script>
      ;(function($){
          $.fn.extend({
              donetyping: function(callback,timeout){
                  timeout = timeout || 1e3; // 1 second default timeout
                  var timeoutReference,
                      doneTyping = function(el){
                          if (!timeoutReference) return;
                          timeoutReference = null;
                          callback.call(el);
                      };
                  return this.each(function(i,el){
                      var $el = $(el);
                      // Chrome Fix (Use keyup over keypress to detect backspace)
                      // thank you @palerdot
                      $el.is(':input') && $el.on('keyup keypress paste',function(e){
                          // This catches the backspace button in chrome, but also prevents
                          // the event from triggering too preemptively. Without this line,
                          // using tab/shift+tab will make the focused element fire the callback.
                          if (e.type=='keyup' && e.keyCode!=8) return;
      
                          // Check if timeout has been set. If it has, "reset" the clock and
                          // start over again.
                          if (timeoutReference) clearTimeout(timeoutReference);
                          timeoutReference = setTimeout(function(){
                              // if we made it here, our timeout has elapsed. Fire the
                              // callback
                              doneTyping(el);
                          }, timeout);
                      }).on('blur',function(){
                          // If we can, fire the event since we're leaving the field
                          doneTyping(el);
                      });
                  });
              }
          });
      })(jQuery);
      
      function validate(value) {
        var regex = /\d/g;
        if (regex.test(value)) {
          $('#error').text('Only text allowed!');
        } else {
          $('#error').empty();
        }
      }
      
      $('input[name=name]').donetyping(function(e){
        validate($(this).val());
      });
      
      </script>
      </body>
      </html>
      

      感谢https://stackoverflow.com/a/14042239/9379378

      【讨论】:

      • 感谢您的解决方案,但我通过additional-methods.js 文件找到了解决方案
      • $("form[name='book']").validate({ //上键验证 onkeyup: function(element) { $(element).valid(); },
      【解决方案3】:

      //jquery validation booking page
      	
      	// Wait for the DOM to be ready
      $(function() {
        // Initialize form validation on the registration form.
        // It has the name attribute "registration"
        $("form[name='book']").validate({
      	  //on key up validation
      	  onkeyup: function(element) {
            $(element).valid(); 
          },  
          // Specify validation rules
          rules: {
            // The key name on the left side is the name attribute
            // of an input field. Validation rules are defined
            // on the right side
            fname: {
              required: true,
              lettersonly: true
              },
            lname:{
              required: true,
              lettersonly: true
              },
            email: {
              required: true,
              // Specify that email should be validated
              // by the built-in "email" rule
              email: true
            },
            password: {
              required: true,
              minlength: 5
            }
          },
          // Specify validation error messages
          messages: {
            fname: {
            required:"Please enter your firstname",
            lettersonly:"Letters allowed only"
            },
            lname: {
            required:"Please enter your lastname",
            lettersonly:"Letters allowed only"
            },
            email: "Please enter a valid email address"
          },
          // Make sure the form is submitted to the destination defined
          // in the "action" attribute of the form when valid
          submitHandler: function(form) {
            form.submit();
          }
        });
      });

      【讨论】:

      • 这是完整的运行JS代码。感谢您的回答
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-21
      • 2010-12-06
      • 1970-01-01
      相关资源
      最近更新 更多