简体   繁体   中英

How can I validate user input (characters and number) with javascript?

From this example I tried to validate user input when a button was clicked.

$("#check_data").click(function () {
    var $userInput = $('#user_input'); //from HTML input box id="user_input"
    var pattern = " /*My user input always be like "AB1234567"*/ ";
    if ($userInput.val() == '' || !pattern.test($userInput.val())) {
        alert('Please enter a valid code.');
        return false;
    }
});

My user input input always be like "AB1234567" with this exact same characters but different 7 digits number. I'm new to Javascript and Jquery, if you have any better way to validate user input, please suggest it.

Thank you.

You can use below regex Expression to check

/[A-Za-z0-9]/g

Your code could be like this

    var _pattern=/[A-Za-z0-9]/g
    if($userInput.val().match(_pattern))
    {
        //your code goes here..
    }

Thanks

You can use the below pattern to check

/^AB\d{7}$/

You can change code to

var pattern = '/^AB\d{7}$/';
  if ($userInput.val() == '' || !pattern.test($userInput.val()))
  {
     alert('Please enter a valid code.');
     return false;
  }

\\d{7} matches 7 digits in the range [0-9]

You can follow below code for this:

if ($userInput.val().match(/[^a-zA-Z0-9 ]/g))
{
    // it is a valid value.

} else {
    // show error here
}

Hope it helps you.

Try this one.

$("#check_data").click(function(){
  var $userInput = $('#user_input').val();
  var pattern = /^AB[0-9]{7}?/g;
  if(!$userInput.match(pattern)){
      alert('Please enter a valid code.');
      return false;
  }
});

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