简体   繁体   English

如何在Javascript(Jquery)中定义Validator函数来验证输入字段?

[英]How can I define a Validator function in Javascript (Jquery) to validate an input field?

I want to define a function to validate if an input field is a valid personal id or not! 我想定义一个函数来验证输入字段是否为有效的个人ID! I have the function as you can see : 您可以看到我的功能:

function checkMeliCode(code)
{
    if(!/^\d{8,10}$/.test(code) || /^(0{8,10}|1{8,10}|2{8,10}|3{8,10}|4{8,10}|5{8,10}|6{8,10}|7{8,10}|8{8,10}|9{8,10})$/.test(code))
        return false;
    var L=code.length, _=0;
    for(i=0;i<L-1;i++)
        _+=code.charAt(i)*(L-i);
    _%=11;
    return (code.charAt(L-1)==((_<2)?_:11-_))
}

I'm using a wizard form On Rails .This is The JavaScript code I have in View: 我正在使用向导表单On Rails 。这是View中的JavaScript代码:

$(function() {

$("#wizard").steps();
$("#form").steps({
  bodyTag: "fieldset",
  onStepChanging: function (event, currentIndex, newIndex) {
      // Always allow going backward even if the current step contains invalid fields!
      if (currentIndex > newIndex) {
          return true;
      }

      // Forbid suppressing "Warning" step if the user is to young
      if (newIndex === 3 && Number($("#age").val()) < 18) {
          return false;
      }

      var form = $(this);

      // Clean up if user went backward before
      if (currentIndex < newIndex) {
          // To remove error styles
          $(".body:eq(" + newIndex + ") label.error", form).remove();
          $(".body:eq(" + newIndex + ") .error", form).removeClass("error");
      }
      // Disable validation on fields that are disabled or hidden.
      form.validate().settings.ignore = ":disabled,:hidden";

      // Start validation; Prevent going forward if false
      return form.valid();
  },
  onStepChanged: function (event, currentIndex, priorIndex) {
      // Suppress (skip) "Warning" step if the user is old enough.
      if (currentIndex === 2 && Number($("#age").val()) >= 18) {
          $(this).steps("next");
      }

      // Suppress (skip) "Warning" step if the user is old enough and wants to the previous step.
      if (currentIndex === 2 && priorIndex === 3) {
          $(this).steps("previous");
      }
      switch (priorIndex){
        case 0:
          console.log("my log");
          send_basic_info();
          break;
        // case 1:
        //   send_education();
        //   break;
        // case 2:
        //   send_experience();
        //   break;
        // case 3:
        //   send_laguages();
        //   break;
        // case 4:
        //   send_computer_skill();
        //   break;
        // case 5:
        //   send_computer_certificate();
        //   break;

      }


  },
  onFinishing: function (event, currentIndex) {
      var form = $(this);

      // Disable validation on fields that are disabled.
      // At this point it's recommended to do an overall check (mean ignoring only disabled fields)
      form.validate().settings.ignore = ":disabled";

      // Start validation; Prevent form submission if false
      return form.valid();
  },
  onFinished: function (event, currentIndex) {
      var form = $(this);

      // Submit form input
      // form.submit();
      $.ajax({
        url: "/resume/finished",
        data: null,
        dataType: "json",
        type: "post",
        success: function(data){
          document.location.href="/";
        }
      });
  }
}).validate({
          errorPlacement: function (error, element) {
              element.before(error);
          },
          rules: {
              confirm: {
                  equalTo: "#password"
              }
          }
      });
});

and this is the input I want it to be validated : 这是我希望对其进行验证的输入:

<div>
   <label>*National ID</label>
   <input name="bi-national-id" type="text" placeholder="Enter your National ID" id="national_id" class="form-control required" ><br>
</div>

The thing is I really don't know the difference between .validate() and .validation(). 问题是我真的不知道.validate()和.validation()之间的区别。 The assets has been added (form validation and validate). 资产已添加(表单验证和验证)。

I've Got the answer Enjoy it :) 我得到了答案,享受它:)

   $("#form").steps({ .... }).formValidation({
      framework: 'bootstrap',
            icon: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {

                bi_national_id: {
                    validators: {
                          callback: {
                            message: 'Enter a Valid National ID',
                            callback: function       isValidIranianNationalCode(input) {
                                 if (!/^\d{10}$/.test(input))
                                 return false;
                            var check = parseInt(input[9]);
                            var sum = [0, 1, 2, 3, 4, 5, 6, 7, 8]
                           .map(function (x) { return parseInt(input[x]) * (10 - x); })
                           .reduce(function (x, y) { return x + y; }) % 11;
                           return sum < 2 && check == sum || sum >= 2 && check + sum == 11;
                                }
                          } 
                    }
                },

            }
        })

I used FormValidation. 我使用了FormValidation。 For more Info and Examples Click here . 有关更多信息和示例,请单击此处

Break a Leg 断腿

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

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