简体   繁体   中英

Validation Using jQuery and Regular Expressions

i need regular expression for number started with 0 and the length of this number is 11

i find this regular expression for numbers but this is not for length and 0 at started

$('#myModal #transfer_charge_model_mob').keyup(function () {
            var inputVal = $(this).val();
            var numericReg = /^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/;
            if (!numericReg.test(inputVal)) {
                $('#myModal #transfer_charge_model_mob_lbl').text('please enter number');
                $(this).val('');
            }
            else {
                $('#myModal #transfer_charge_model_mob_lbl').text('');
            }
        });

You can do this without regex.

var x = $(this).val();
var y = x * 1;
if(!isNaN(y))
   if (x.charAt(0) === '0' && x.length == 11)
     //do whatever

You've overcomplicated your regex:

^0\d{10}$

is sufficent.

Converting my comment to an answer, seeing how popular it was

Note the on("change") rather than the keyup

$('#transfer_charge_model_mob').on("change",function () {
   var inputVal = $(this).val();
   var txt = /^0\d{10}$/.test(inputVal)?"":'please enter number';     
   $('#transfer_charge_model_mob_lbl').text(txt);
   if (txt) $(this).val('');
 });

For Keyup you might try

Live Demo

$(function() {
  $('#transfer_charge_model_mob')
    .on("change",function () {
       var inputVal = $(this).val();
       var txt = /^0\d{10}$/.test(inputVal)?"":'please enter number';     
       $('#transfer_charge_model_mob_lbl').text(txt);
       //if (txt) $(this).val(''); // Very harsh if a typo
     })
  .on("keyup",function(e) {
     var val = $(this).val(); 
     var reg =  /[^0-9]/g;
     if (val.match(reg)) { 
         $(this).val(val.replace(reg,""));
     }
  });    
});    
var reg = /^0\d{10}$/;
console.log(reg.test("01111111111"));

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