Social Security Number input validation

前端 未结 2 1722
广开言路
广开言路 2021-01-15 02:57

I have this sample:

link

CODE HTML:



        
相关标签:
2条回答
  • 2021-01-15 03:30

    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()">

    0 讨论(0)
  • 2021-01-15 03:42

    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 is another way to enforce user always enters that 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}">
    
    0 讨论(0)
提交回复
热议问题