sam sam - 2 months ago 7
jQuery Question

Cannot Validate specific account number using jquery validation

I am trying to validate if the account number is 00000000 then throw validation error, I please need some help or direction on how I may achieve this validation for specific numeric values or to restrict user entering 00000000?

jQuery.validator.addMethod("myRule", function (value, element, params) {
return this.optional(element) || value== params[0];
}, "Account number 00000000 is invalid");

$('#myform').validate({ // initialize the plugin
submitHandler: function (form) {
console.log("Submitted!");
},
rules: {
accountNumber: {
required: true,
minlength: 8,
maxlength: 8,

/*MyRule solution found online but not working as expected any other option I could try within JQUERY Validator????*/

myRule: ["00000000"],
digits: true
},
companyNumber: {
required: true,
digits: true

}
},

messages: {
accountNumber: {
digits: 'Account Number must be an number',
minlength: 'Account number cannot be less than 8 digits',
maxlength: 'Account number cannot be more than 8 digits',
required : 'Account number is required'
},
companyNumber: {
digits: 'Company number must be a number',
required : 'Company number is required'

}
}
});

Answer

you need value != params[0] (not equal) to be valid.

see a working example below:-

jQuery.validator.addMethod("myRule", function(value, element, params) {
  return this.optional(element) || value != params[0];
}, "Account number 00000000 is invalid");

$('#myform').validate({ // initialize the plugin
  submitHandler: function(form) {
    console.log("Submitted!");
  },
  rules: {
    accountNumber: {
      required: true,
      minlength: 8,
      maxlength: 8,

      /*MyRule solution found online but not working as expected any other option I could try within JQUERY Validator????*/

      myRule: ["00000000"],
      digits: true
    },
    companyNumber: {
      required: true,
      digits: true

    }
  },

  messages: {
    accountNumber: {
      digits: 'Account Number must be an number',
      minlength: 'Account number cannot be less than 8 digits',
      maxlength: 'Account number cannot be more than 8 digits',
      required: 'Account number is required'
    },
    companyNumber: {
      digits: 'Company number must be a number',
      required: 'Company number is required'

    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.js"></script>

<form id="myform">
  <input type="text" name="accountNumber" />
  <input type="text" name="companyNumber" />
  <input type="submit" value="submit"/>
  </form>

Comments