Avatar of movieprodw
 asked on

javascript check input pattern and add class if correct pattern


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'

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

Open in new window


Avatar of undefined
Last Comment
Julian Hansen

8/22/2022 - Mon
Leonidas Dosas

Comments inside the codes:
	.nosnmatch { border: solid 2px blue; }
	.snmatch { border: solid 2px green;	}
<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" />

Open in new window

JQuery code:

//Via JQuery I target the input element.I use keydown so
//to get and the backspace key function
   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();
//With an if condition I check initially the lenght of the string
//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.

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
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
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