0

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.

3
  • So the value is in the pattern of AB1234567, but it's not the exact value? Sounds like you need to use regular expressions. Commented Feb 20, 2019 at 11:47
  • try this pattern ^AB[0-9]{7}? Commented Feb 20, 2019 at 11:48
  • the pattern you need: [a-zA-Z]{2}[0-9]{7} suppose to be any letter max 2 any number max 7 Commented Feb 20, 2019 at 11:52

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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]

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.