javascript - Social Security Number input validation -


i have sample:

link

code html:

<input class="required-input" id="ssn" maxlength="9" type="text" name="ssn" placeholder="123-45-6789"> 

code css:

.valid{   border:1px solid blue; } .invalid{   border:1px solid red; } 

code js:

function ssnformat(){     $("#ssn").on('blur change', function () {         text = $(this).val().replace(/(\d{3})(\d{2})(\d{4})/, "$3-$2-$4");         if ($(this).val() == '' || $(this).val().match(text) || $(this).val().length == 0) {             $(this).removeclass('valid').addclass('invalid');         }else {             $(this).removeclass('invalid').addclass('valid');         }     }); }  $( "#ssn" ).on('blur change', function() {         ssnformat();     }); 

what want these things are:

1.if write following text want validate format 123-12-1234

2.if write 123456789 want transform when click outside input in format

123-12-1234 

i tried using function below don't work

$("#ssn").on("click", function() {         var thisval = $(this).val();         var value = thisval.replace(/[^\/\d]/g,''); //here problem         $(this).val(value);     }); 

can please me solve problem?

thanks in advance!

try this

function myfunc() {     var patt = new regexp("\d{3}[\-]\d{2}[\-]\d{4}");     var x = document.getelementbyid("ssn");     var res = patt.test(x.value);     if(!res){      x.value = x.value          .match(/\d*/g).join('')          .match(/(\d{0,3})(\d{0,2})(\d{0,4})/).slice(1).join('-')          .replace(/-*$/g, '');     }  }
.valid{    border:1px solid blue;  }  .invalid{    border:1px solid red;  }
<input class="required-input" id="ssn" type="text" name="ssn" placeholder="123-45-6789" onblur = "myfunc()">

also there way enforce user enters pattern -

<input class="required-input" id="ssn" type="text" name="ssn" placeholder="123-45-6789" onblur = "myfunc()" required pattern="\d{3}[\-]\d{2}[\-]\d{4}"> 

Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -