简体   繁体   English

使用Jquery插件和其他方法进行表单验证

[英]Form validation using Jquery plugin and additional methods

I want to use the jquery plugin for validating my form with letters only in name section. 我想使用jquery插件仅在名称部分使用字母来验证我的表单。 such that when a user enters special characters or numbers it gives an error. 这样,当用户输入特殊字符或数字时会出现错误。 Also i want to check the form validation as the users types the information ie realtime validation before submitting the form. 我也想检查表单验证,因为用户键入信息即提交表单之前的实时验证。

 //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> 

I want to use the jquery plugin for validating my form with letters only in name section. 我想使用jquery插件仅在名称部分使用字母来验证我的表单。 such that when a user enters special characters or numbers it gives an error 这样,当用户输入特殊字符或数字时会出现错误

      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

How about doing something like this? 怎么做这样的事情?

<!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>

Credits to this https://stackoverflow.com/a/14042239/9379378 归功于此https://stackoverflow.com/a/14042239/9379378

 //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(); } }); }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM