简体   繁体   中英

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

$(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(). 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. For more Info and Examples Click here .

Break a Leg

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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