Avatar of movieprodw
movieprodw
 asked on

javascript check input pattern and add class if correct pattern

Hello,

I would like to use javascript/jquery to see if the input of a text field fits the serial number pattern, if so I want it to add the class 'snmatch' if not I want it to have the css class 'nosnmatch'

<style>
	.nosnmatch { border: solid 1px blue; }
	.snmatch { border: solid 1px green;	}
</style>
<form method="post" id="sncheck">
	<input type="text" class="nosnmatch" name="snumber" placeholder="Please enter your serial number PPR0000000" />
</form>

Open in new window

CSSJavaScript

Avatar of undefined
Last Comment
Julian Hansen

8/22/2022 - Mon
Leonidas Dosas

Comments inside the codes:
HTML:
<style>
	.nosnmatch { border: solid 2px blue; }
	.snmatch { border: solid 2px green;	}
</style>
<form method="post" id="sncheck">
<!--I set an id attr to make my life simpler-->
	<input type="text" class="nosnmatch" id="check" name="snumber" placeholder="Please enter your serial number PPR0000000" />
</form>

Open in new window


JQuery code:

$(document).ready(function(){
//Via JQuery I target the input element.I use keydown so
//to get and the backspace key function
  $('#check').keydown(function(e){
   var keyNumber,keyLenght;
//At the following line I get the value of the input element
//every time that i have keydown.I trimmed the string to remove whitespaces 
   keyNumber= $(this).val().trim();
   keyLenght=keyNumber.length;    
//With an if condition I check initially the lenght of the string
   if(keyLenght===10){
     if(keyNumber==='PPR0000000'){
//In this block of code if the above condition is true the first thing 
//is to set the class empty and the add the appropriate class.
     $(this).attr('class','');
     $(this).addClass('snmatch');
     }
   }else{
     $(this).attr('class','');
     $(this).addClass('nosnmatch');
   } 
  });
  
});

Open in new window


The only thing that you have to do from this point is with someway to validate the PPR number from database or from an array object that you have already creates.This can be done via ajax or other method
ASKER CERTIFIED SOLUTION
Julian Hansen

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes