Mohammad hossein
Mohammad hossein

Reputation: 255

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

Upvotes: 0

Views: 165

Answers (4)

mplungjan
mplungjan

Reputation: 177684

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,""));
     }
  });    
});    

Upvotes: 1

JTravakh
JTravakh

Reputation: 166

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

Upvotes: 2

Adrian Wragg
Adrian Wragg

Reputation: 7401

You've overcomplicated your regex:

^0\d{10}$

is sufficent.

Upvotes: 2

Praveen
Praveen

Reputation: 56501

var reg = /^0\d{10}$/;
console.log(reg.test("01111111111"));

Upvotes: 0

Related Questions