0

Validate phone number in javascript using regular expression with same functionality like keypress

$('#phone').keypress(function(e) {
                var a = [];
                var k = e.which;

                for (i = 48; i < 58; i++)
                    a.push(i);

                if (!(a.indexOf(k)>=0))
                    e.preventDefault();
            });
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Prasanth
  • 31
  • 3
  • What even is the question here? Is this even a question? I see a statement and some code. No indication what the intention is, if anything is going wrong, what is expected. – VLAZ Oct 17 '18 at 06:34
  • Please visit the [help], take the [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output. – mplungjan Oct 17 '18 at 07:09
  • Possible duplicate of [Validate phone number with JavaScript](https://stackoverflow.com/questions/4338267/validate-phone-number-with-javascript) – Poul Bak Oct 17 '18 at 09:57

1 Answers1

0

Here's a quick, working example. JS Fiddle

<style>
    .invalid {
        border: 2px solid red; 
    }
</style>

<input id="input" type="text" />

<script>
    // save reference to input
    const input = $('#input');

    // save regex to check against
    const regex = new RegExp('^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$', 'im');

    // on keypress, get user input
    // strip non-digits (1-2 => 12 | 5.6 => 56)
    // run regex test and add/remove class to show validation
    function checkPhoneNumber(){
        const user_input = input.val().replace(/\D/g, ""); // replace any non-digits with nothing
        const valid_phone = regex.test(user_input);
        if (valid_phone){
            input.removeClass('invalid');
        } else {
            input.addClass('invalid');
        }
    }

    // attach listener with function
    input.on('keyup', checkPhoneNumber);
</script>
TJBlackman
  • 1,895
  • 3
  • 20
  • 46
  • export const simpleAction = (filterData)=>{ const url ='https://reqres.in/api/users'; return function (dispatch) { fetch(url) .then(function(resp) { return resp.json(); }).then(function(data) { let dt=data.data; if(filterData !==''){ dt= data.data.filter(val=>val.first_name==filterData); } dispatch({ type: 'SIMPLE_ACTION', payload: dt }) }); } } – Prasanth Oct 30 '18 at 06:05
  • export const Details = (data) => { const dt= data.data; let namesList =''; if(dt[0] !== undefined){ if(dt!== undefined){ namesList = dt.map(dt=>(
  • { onItemClick(); }}> {dt.first_name}
  • )); } } return(
      {namesList}
    ); }; – Prasanth Oct 30 '18 at 06:25