Validating inputs using JavaScript RegEx - javascript

I'm having this JS function to verify the user input and ensure it's a year between 2000-2021, it's working great, the problem is when I write invalid input it changes the outline to red, however when I write a valid input it's remain red. And even if I write valid input from the beginning it goes red.
var batchRegex=/^[2][0][0-2][0-1]$/;
function checkBatch(batch){
if (batch = ""){
document.getElementById('batch').style.outlineColor = "red";
}
else if(!batchRegex.test(batch)){
document.getElementById('batch').style.outlineColor = "red";
}
else if(batchRegex.test(batch)){
document.getElementById('batch').style.outlineColor = "none";
}
}
<form method="post">
<input type="text" maxlength="4" id="batch" name="batch" onkeyup="checkBatch(this.value)" required>
<input type="submit" name="submit">
</form>

You have multiple issues in your code:
if (batch = ""){ should be if (batch == ""){
the regex /^[2][0][0-2][0-1]$/ matches only the values:
2000, 2001, 2010, 2011, 2020, 2021
but you want to match all values between 2000 and 2021.
Why not just try something simple like this:
function checkBatch(batch){
if (batch.value >= 2000 && batch.value <= 2021){
batch.style.outlineColor = "green";
} else {
batch.style.outlineColor = "red";
}
}
<form method="post">
<input type="text" maxlength="4" id="batch" name="batch" onkeyup="checkBatch(this)" required>
<input type="submit" name="submit">
</form>
and instead of changing inline styles via javascript, just add a class where you can then change the style with CSS something like..
function checkBatch(batch){
if (batch.value >= 2000 && batch.value <= 2021){
batch.classList.remove('alert')
batch.classList.add('success')
} else {
batch.classList.remove('success')
batch.classList.add('alert')
}
}
input.alert {
outline-color: red;
}
input.success {
outline-color: green;
}
<form method="post">
<input type="text" maxlength="4" id="batch" name="batch" onkeyup="checkBatch(this)" required>
<input type="submit" name="submit">
</form>

Don't use JS to change the style of the input, use the built in input validation available within HTML5 and CSS. Use CSS to automatically handle and update the style.
If instead you use a number input you can place min and max values
<input type="number" min=2000 max=2021 name="numyr" required >
You can then use css using the :invalid pseudo element.
input:invalid {
outline: 2px solid pink;
}
If you're adamant about using a regex on an input value then you can use the pattern attribute
<input type="text" pattern="^[2][0][0-2][0-1]$" >
It's still possible to do further validation before submit using the form submit event.
var batchRegex=/^[2][0][0-2][0-1]$/;
function checkBatch(batch){
if (batch = ""){
document.getElementById('batch').style.outlineColor = "red";
}
else if(!batchRegex.test(batch)){
document.getElementById('batch').style.outlineColor = "red";
}
else if(batchRegex.test(batch)){
document.getElementById('batch').style.outlineColor = "none";
}
}
input{
min-width: 100px;
display: block;
margin: 5px;
}
input:invalid {
outline: 2px solid pink;
}
<form method="post">
<input type="text" maxlength="4" id="batch" name="batch" onkeyup="checkBatch(this.value)" required>
<input type="number" min=2000 max=2021 name="numyr" required >
<input type="text" pattern="^[2][0][0-2][0-1]$" required >
<input type="submit" name="submit">
</form>

Related

Best way to disable and enable textboxes

I'm writing a simple html code that does enable and disable some textboxes on button clicks. Below is my code.
function myFunction1() {
document.querySelector('#myText0').disabled = true;
document.querySelector('#myText1').disabled = true;
document.querySelector('#myText2').disabled = false;
document.querySelector('#myText3').disabled = false;
document.querySelector('#myText4').disabled = false;
}
function myFunction2() {
document.querySelector('#myText0').disabled = false;
document.querySelector('#myText1').disabled = false;
document.querySelector('#myText2').disabled = true;
document.querySelector('#myText3').disabled = true;
document.querySelector('#myText4').disabled = true;
}
function myFunction3() {
document.querySelectorAll("input").disabled = true;
document.querySelector('#myText2').disabled = false;
document.querySelector('#myText3').disabled = false;
document.querySelector('#myText4').disabled = false;
}
function myFunction4() {
document.querySelector("input").disabled = true;
document.querySelector('#myText0').disabled = false;
document.querySelector('#myText1').disabled = false;
}
input{
display:block;
margin:0.85em
}
<input type="text" id="myText0" label="myText0" disabled>
<input type="text" id="myText1" label="myText1" disabled>
<input type="text" id="myText2" label="myText2" disabled>
<input type="text" id="myText3" label="myText3" disabled>
<input type="text" id="myText4" label="myText4" disabled>
<h2>
Manually Enabling text boxes
</h2>
<button onclick="myFunction1()">Disable 0,1 field</button>
<button onclick="myFunction2()">Disable Rest field other than 0,1</button>
<br/>
<h2>
Disabling All initially and then enabling the required text boxes
</h2>
<button onclick="myFunction3()">Disable 0,1 field</button>
<button onclick="myFunction4()">Disable Rest field other than 0,1</button>
I've got a total of 120 textboxes so I'm looking for a better way to do this. In my above code, the buttons under Manually Enabling text boxes are working as expected. Whereas, the other approach that I thought of under Disabling All initially and then enabling the required text boxes is not working as expected.
Also Please let me know if there is a better approach than what I've used as there are 120 textboxes and my approach is the most time-taking as I'm checking manually and my 2nd approach is saving 25% of the total time (considering 120 textboxes and the number of them to be disabled that were provided as part of my SRS).
Thanks
You can make simple common methods that will 'cascade' the logic for you rather than defining each operation repeatedly. Take a look at the attached fiddle (and its code snippet)
function myFunc1() {
enableAll();
disableTextbox('#myText0');
disableTextbox('#myText1');
}
function myFunc2() {
disableAll();
enableTextbox('#myText0');
enableTextbox('#myText1');
}
/* Common functions */
function disableAll() {
disableTextbox('#myText0');
disableTextbox('#myText1');
disableTextbox('#myText2');
disableTextbox('#myText3');
disableTextbox('#myText4');
}
function enableAll() {
enableTextbox('#myText0');
enableTextbox('#myText1');
enableTextbox('#myText2');
enableTextbox('#myText3');
enableTextbox('#myText4');
}
function disableTextbox(textboxName) {
document.querySelector(textboxName).disabled = true;
}
function enableTextbox(textboxName) {
document.querySelector(textboxName).disabled = false;
}
/* Common functions */
input{
display:block;
margin:0.85em
}
<input type="text" id="myText0" label="myText0" disabled>
<input type="text" id="myText1" label="myText1" disabled>
<input type="text" id="myText2" label="myText2" disabled>
<input type="text" id="myText3" label="myText3" disabled>
<input type="text" id="myText4" label="myText4" disabled>
<h1>Proper way to do it</h1>
<button onclick="myFunc1()">Disable 0,1 field</button>
<button onclick="myFunc2()">Disable Rest field other than 0,1</button>
you can use for, and for each "input type" or "class":
function myFunction1() {
//var inputs = document.querySelectorAll('input[type=text]'); //use this or below
var inputs = document.querySelectorAll('input[class=ttt]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = false; // or true
//inputs[i].style.display = 'none';
}
}
function myFunction2() {
//var inputs = document.querySelectorAll('input[type=text]'); //use this or below
var inputs = document.querySelectorAll('input[class=ttt]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = true; // or false
//inputs[i].style.display = 'none';
}
}
input{
display:block;
margin: 0.85em
}
<input type="text" id="myText0" class="ttt" label="myText0" disabled>
<input type="text" id="myText1" class="ttt" label="myText1" disabled>
<input type="text" id="myText2" class="ttt" label="myText2" disabled>
<input type="text" id="myText3" class="ttt" label="myText3" disabled>
<input type="text" id="myText4" class="ttt" label="myText4" disabled>
<h2>
Manually Enabling text boxes
</h2>
<button onclick="myFunction1()">enable all field</button>
<button onclick="myFunction2()">disable all field</button>
I think the best way to do this is to specify the reason for disabling in a class or even a data attribute. For simplicity let's use a class. So for example an input should be disabled because of any reason you give it a class (or data attr) with the value of the name of that reason. This will make your code very readable even without reading over the javascript files. And you will not write much of javascript at all.
That would make your elements that should be enabled together, together, and vice versa.
I would suggest this solution:
function disable(className) {
for (const element of document.getElementsByClassName(className)) {
element.disabled = true;
}
}
function enable(className) {
for (const element of document.getElementsByClassName(className)) {
element.disabled = false;
}
}
input{
display:block;
margin:0.85em
}
<input type="text" class="reason1" label="myText0" disabled>
<input type="text" class="reason1" label="myText1" disabled>
<input type="text" class="reason2" label="myText2" disabled>
<input type="text" class="reason2" label="myText3" disabled>
<input type="text" class="reason2" label="myText4" disabled>
<h2>
Manually Enabling text boxes
</h2>
<button onclick="disable('reason1'); enable('reason2')">Disable 0,1 field</button>
<button onclick="disable('reason2'); enable('reason1')">Disable Rest field other than 0,1</button>
<br />
<h2>
Disabling All initially and then enabling the required text boxes
</h2>
<button onclick="disable('reason1'); enable('reason2')">Disable 0,1 field</button>
<button onclick="enable('reason1'); disable('reason2')">Disable Rest field other than 0,1</button>

How to check if two fields match in javascript?

Im new to javascript and i have this kind of problem. I have two fields and they must be checked if the input inside is the same. If they are the same an alert should popup to tell so. Thanks in advance.
Here is an example of my fields:
function writeText() {
n = "has been collected " + window.document.myform.exemplu1.value;
document.getElementById("content").innerHTML = n;
}
function writePass() {
n = window.document.myform.exemplu2.value;
alert("password is " + n);
}
<div>
<h3> Example</h3>
<form name="myform">
<p> <input name="exemplu1" type="text" value="Edit field" onBlur="writeText()" size="25" maxlength="30" />
<span id="content"> </span></p>
<p> <input name="exemplu2" type="password" value="Parola" onBlur="writePass()" size="15" maxlength="15" /></p>
</form>
</div>
Use the strict equality operator.
I have bound a callback using adEventListener to the click event of a button to perform the check.
const buttonEl = document.querySelector('button')
const usernameEl = document.getElementById('username')
const passwordEl = document.getElementById('password')
buttonEl.addEventListener('click', () => usernameEl.value === passwordEl.value ? console.log('They are the same') : console.log('They are different'))
* {
color: #DDD;
background-color: white;
font-size: 1.1em;
padding: 10px;
margin: 10px;
}
<input type="text" id="username" />
<input type="password" id="password" />
<button>Check</button>

JQuery addClass working in a very odd manner

I have a form with 3 inputs: 2 text inputs for a Username and E-mail and a third password input for, you guessed it, a password.
I'm validating these input fields in JQuery and when an input is either empty or doesn't match it's format, it adds a class to the input with a red border. The code goes as follows:
if ($("input#username").val().length < 6) {
$("input#username").addClass('input-error');
next_step = false;
} else if (!isEmail($("#email").val())) {
$("#email").addClass('input-error');
next_step = false;
} else if (!isPassword($("#pwd").val())) {
$("#pwd").addClass('input-error');
next_step = false;
}
else {
$(this).removeClass('input-error');
next_step = true;
}
It works perfectly with both Username and E-mail fields, and it also works if the Password field is empty, but even though it validates perfectly, the addClass() doesn't work if the Password doesn't meet it's requirements (At least one Uppercase letter and one number).
This is what the browser console shows:
As you can see, it kind of adds the class, but then not really.
What is happening? If you need the HTML code and/or the CSS code, tell me!
Thanks for your attention!
EDIT
Here is the HTML and CSS as requested:
<fieldset>
<div class="form-bottom">
<img src="img/gbsnlogo.svg" alt="GBSN Research" name="GBSN Research" width="50%" class="signupLogo" />
<br>
<br>
<br>
<div class="form-group">
<label for="username"><h1>USERNAME:</h1></label>
<input type="text" class="form-control" id="username" placeholder="Enter username..." name="username">
</div>
<div class="form-group">
<label for="email"><h1>E-MAIL:</h1></label>
<input type="text" class="form-control" id="email" placeholder="Enter e-mail..." name="email">
</div>
<div class="form-group">
<label for="pwd"><h1>PASSWORD:</h1></label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password..." name="pwd">
</div>
<div class="text-center">
<button type="button" class="btn-next btn-nav"><h1>NEXT</h1></button>
</div>
</div>
</fieldset>
and the CSS:
.form-control {
height: 40px;
border: 2px solid black;
border-radius: 0;
font-size: 14px;
}
.form-control:focus {
border: 2px solid black;
box-shadow: 0;
}
.input-error {
border-color: #FF2859;
}
This is working for me.
Please comment what is still not working if you have this kind of setup?
function isEmail(email) { // dummy example
return email.indexOf("#")>1;
}
function isPassword(passwd) { // dummy example
return passwd.indexOf("x")>=0; // must contain x
}
$(function() {
$(".btn-next").on("click", function() {
$(".form-group input").removeClass('input-error');
var next_step = true,
user = $("#username").val(),
email = $("#email").val(),
pwd=$("#pwd").val();
if (user.length < 6) {
$("#username").addClass('input-error');
next_step = false;
} else if (!isEmail(email)) {
$("#email").addClass('input-error');
next_step = false;
} else if (!isPassword(pwd)) {
$("#pwd").addClass('input-error');
next_step = false;
}
console.log(next_step);
});
});
.form-control {
height: 40px;
border: 2px solid black;
border-radius: 0;
font-size: 14px;
}
.form-control:focus {
border: 2px solid black;
box-shadow: 0;
}
.input-error {
border-color: #FF2859;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<fieldset>
<div class="form-bottom">
<img src="img/gbsnlogo.svg" alt="GBSN Research" name="GBSN Research" width="50%" class="signupLogo" />
<br>
<br>
<br>
<div class="form-group">
<label for="username"><h1>USERNAME:</h1></label>
<input type="text" class="form-control" id="username" placeholder="Enter username..." name="username">
</div>
<div class="form-group">
<label for="email"><h1>E-MAIL:</h1></label>
<input type="text" class="form-control" id="email" placeholder="Enter e-mail..." name="email">
</div>
<div class="form-group">
<label for="pwd"><h1>PASSWORD:</h1></label>
<input type="text" class="form-control" id="pwd" placeholder="Enter password..." name="pwd">
</div>
<div class="text-center">
<button type="button" class="btn-next btn-nav"><h1>NEXT</h1></button>
</div>
</div>
</fieldset>
From what I see from the image you posted
I can only speculate this is what happened.
The line [input#pwd.form-control.input-error] was evaluated immediately when it got printed to the console. So that mean at that time, the dom does have the class input error in it. However, when you expand it, the dom got re-evaluated again. And at that time, the dom's class input-error got removed, so you don't see it anymore. I was able to prove this by running $('#pwd').addClass('input-error') and $('#pwd').removeClass('input-error') in that order, image below
Based on that, I suspect you have another logic in the code that remove the class shortly after you have added the class to the dom, highly possibly $(this).removeClass('input-error');.

Getting JavaScript oninput function to change background color?

i have some code that works for a password form where the user is filling out their details and then 2 of the boxes only work or become typable if they enter a number/age greater than that specified. i now want to take it one step further and make it obvious to the user that those boxes are only editable certain times by colouring them in a different colour. for some reason though the new code within the JS is not working.
code is below:
<div class="container">
<div class="jumbotron" id="firstform">
<h1>Sign up page</h1>
<form id="myform">
<label>Username </label> <input type="text" name="uname" id="uname" data-placement="bottom" title="" data-original-title="Username must be unique" class="mytooltip"><br>
<div class="pwordCheck">
<label>Password </label> <input type="password" id="pword" data-placement="bottom" title="" onkeyup="passwordValidation(); return false;" data-original-title="Password must be more than 6 characters long" class="mytooltip"><br>
<label>Confirm Password </label> <input type="password" id="confpword" onkeyup="passwordValidation(); return false;" data-placement="bottom" title="" data-original-title="Passwords must match" class="mytooltip">
<span id="themessage" class="themessage"></span><br>
</div>
<label>Email </label> <input type="email" id="e-mail"><br>
<label>Age </label> <input type="number" id="age" oninput="ifOfAge(); return false;"><br>
<label>Can you drive? </label> <input type="text" id="drive" disabled><br>
<label>What is your occupation? </label> <input type="text" id="occupation" disabled><br>
<input type="submit" value="Submit" onclick="usernameAlreadyExists(); return false;">
</form>
</div>
</div>
css:
input#drive{
background-color: #999;
}
input#occupation{
background-color: #999;
}
js:
function ifOfAge() {
var age = document.getElementById("age");
var drive = document.getElementById("drive");
var occupation = document.getElementById("occupation");
var white = "#fff";
if (age.value >= 21) {
drive.disabled = false;
occupation.disabled = false;
} else if (age.value >= 16) {
drive.disabled = false;
occupation.style.backgroundColor = white;
} else {
drive.disabled = true;
occupation.disabled = true;
drive.style.backgroundColor = white;
occupation.style.backgroundColor = white;
}
}
Color must be enclosed within quotes. Like below. Wherever you have used white surround it with quotes
drive.style.backgroundColor = "white";
you can make change color for disabled input like this.
EDIT
function ifOfAge() {
var age = document.getElementById("age");
var drive = document.getElementById("drive");
var occupation = document.getElementById("occupation");
var white = "#fff";
if (age.value >= 21) {
drive.disabled = false;
occupation.disabled = false;
} else if (age.value >= 16) {
drive.disabled = false;
occupation.style.backgroundColor = white;
} else {
drive.disabled = true;
occupation.disabled = true;
drive.style.backgroundColor = "#999";
occupation.style.backgroundColor = "#999";
}
}
You can make it more nice if you used jQuery and plugin jQuery Validation or even more nice with this one.

Trigger Similar JQuery element on different span element

So ideally what I want to have happen is trigger an identical function that I already have in my email span/form element, however I'm new to JQuery and can't quite wrap my head around it. Anyways, so in my email function, it essentially grabs the user input and and triggers the css class "form span error" which turns the span element red. Until the user inputs the "#" symbol, the "form span valid" is triggered. I would additionally like JQuery to trigger the "form span.error" rule on the productId forum/span element. Could please someone explain? Here's the CSS rule for the span:
#form span {
border-radius: 20px;
margin-left:15px;
padding: 8px 35px;
background: #FA5700;
color:#faf3bc;
}
#form span.valid {
background-color :#c0ce51;
color: #faf3bc;
}
#form span.error {
background-color:#b0240f;
color: #faf3bc;
}
HTML/JQUERY:
<form method="post" action="contact-thanks.php">
<p>
<label for="name">Name:</label>
<input type="text" name="name" id="name" class="required" value="<?php if (isset($name)) { echo htmlspecialchars($name); } ?>">
<span>Please enter your name</span>
</p>
<p>
<label for="email">Email:</label>
<input type="text" name="email" id="email" class="required" value="<?php if(isset($email)) { echo htmlspecialchars($email); } ?>">
<span>Please enter a valid email address</span>
</p>
<p>
<label for="productId">Product Id:</label>
<input type="text" name="productId" id="productId" class="required" value="<?php if(isset($productId)) { echo htmlspecialchars($productId); } ?>">
<span>Please enter a ID number</span>
</p>
<p class="submit">
<input type="submit" value="Submit" class="btn-submit">
</p>
</form>
</div>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
var $submit = $(".submit input");
var $required = $(".required");
function containsBlanks(){
var blanks = $required.map(function(){ return $(this).val() == "";});
return $.inArray(true, blanks) != -1;
}
//Checks for valid email
function isValidEmail(email){
return email.indexOf("#") != -1;
}
//Does not let the user submit if all text fields are not filled in
function requiredFilledIn(){
if(containsBlanks() || !isValidEmail($("#email").val()))
$submit.attr("disabled","disabled");
else
$submit.removeAttr("disabled");
}
//Here's what I've tried, I'm playing around with it here for testing purposes
//I'm afraid this syntax is terribly wrong
$("#productId").focus(function(){
$(this).next().removeClass("valid").addClass("error");
});
$("#form span").hide();
$("input,textarea").focus(function(){
$(this).next().fadeIn("slow");
}).blur(function(){
$(this).next().fadeOut("slow");
}).keyup(function(){
//Check all required fields.
requiredFilledIn();
});
$("#email").keyup(function(){
//Check for a valid email.
if(isValidEmail($(this).val()))
$(this).next().removeClass("error").addClass("valid");
else
$(this).next().removeClass("valid").addClass("error");
});
requiredFilledIn();
</script>
Appreciate any help ahead of time!
After some simple experimenting, I figured it out. Here's the code if anyone is curious:
$("#productId").show(function(){
$(this).next().fadeIn("slow").removeClass("valid").addClass("error");
});

Categories

Resources