set Second validation message - javascript

I'm trying to set a Second validation message for my password input, but it doesn't work, can you help me out?
This is my tag:
<input id="password" style="text-align:center;" type="text" name="password"
tabindex="3" pattern="[a-zA-Z0-9].{5,}" title="" required
oninvalid="this.setCustomValidity('Please enter a password')"
oninput="this.setCustomValidity('')"
onkeyup="deleteBadConfirm(); valid_pass();" />
and this is mu js function for the second validation message:
function valid_pass() {
if(document.getElementById("password").value != "") {
document.getElementById("password")
.setCustomValidity('At least, enter 6 characters; Don't use any symbols');
};
};
function deleteBadConfirm() {
$("#confirmpassword").prop("value", "");
};
EDIT: This is how it's supposed to go down:
if the user press submit before entering a password, the message says "please enter a password". Then, if the user enters a password, but it's not valid, this time the message should say"At least, enter 6 ...". Now, it shows the first message, but then, if I enter less than 6 characters, it still brings up the old message, and if I enter 6 invalid characters, it won't show any message!!

You have a error in below line
Change this
document.getElementById("password")
.setCustomValidity('At least, enter 6 characters; Don't use any symbols');
To
document.getElementById("password")
.setCustomValidity('At least, enter 6 characters; Don\'t use any symbols');
by adding a escape character - backslash ()

Clear the oninvalid event or it will always override your setCustomValidity. Added the :invalid CSS pseudo-class to check if value is valid or not.
function valid_pass() {
if (document.getElementById("password").value != "") {
if ($('#password').is(":invalid")) {
document.getElementById("password")
.setCustomValidity('At least, enter 6 characters; Don\'t use any symbols');
};
} else {
document.getElementById("password")
.setCustomValidity('Please enter a password');
};
};
function deleteBadConfirm() {
$("#confirmpassword").prop("value", "");
};
//Added this to show setCustomValidity message/tooltip without submit event
function runReportValidity() {
document.getElementById("password").reportValidity();
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="password" style="text-align:center;" type="text" name="password" tabindex="3" pattern="[a-zA-Z0-9].{5,}" title="" required oninvalid="valid_pass()" oninput="this.setCustomValidity('')" onkeyup="deleteBadConfirm(); valid_pass();" />
<!-- Added this to show setCustomValidity message/tooltip without submit event -->
<input type="button" onClick="runReportValidity()" value="Report Validity">

Related

Check if Form Input is Valid With JavaScript

I am currently trying to make a login / create account page for a website that I am developing for fun. In the create account form, I have an input field for username, name, email, password, and verify password. I also have patterns in the input fields so that the user makes valid account info. Here is the form below:
<form method="post" action="CreateAccount.php">
<h1>Create Account</h1>
<input class="inputInfo" type="text" name="username" id="newUsername" pattern="[A-Za-z0-9]+" placeholder="Username" maxlength="40" minlength="5" onkeyup="checkInput()" onblur="checkInput()" autocomplete="off" required/>
<input class="inputInfo" type="text" name="fullname" id="newName" placeholder="First and Last Name" onkeyup="checkInput()" onblur="checkInput()" minlength="3" autocomplete="off" required/>
<input class="inputInfo" type="email" name="email" id="newEmail" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,}$" title="Must be a real email" placeholder="Email" onkeyup="checkInput()" onblur="checkInput()" required/>
<input class="inputInfo" type="password" name="password" id="newPassword" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" placeholder="Password"
title="Must be 8 or more characters with at least one number or special character, uppercase letter, and lowercase letter" onkeypress="checkInput()" onblur="checkInput()" required/>
<input class="inputInfo" type="password" name="verifypassword" id="verifyPass" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" placeholder="Verify Password"
title="Must be 8 or more characters with at least one number or special character, uppercase letter, and lowercase letter" onkeypress="checkInput()" onblur="checkInput()" required/>
<span><label for="showp"><input type="checkbox" id="showp" onclick="showPassword()">Show Password</label></span>
<button type="submit" style="margin-top: 7px;" class="disabled" id="submitButton">Sign Up</button>
<p style="font-size: 10px;">By signing up, you agree to our Terms , Data Policy and Cookies Policy .</p>
</form>
For clarification: the username pattern requires you to have a username with only upper and lower case letters and numbers and must be at least 5 characters and at most 40 characters. The email requires you to input a valid email address pattern. And the password requires a password that is at least 8 characters and must have an uppercase and lowercase letter and a number or special character.
In the input fields, you will see that I have a function called during blur or keyup event that is called checkInput(). The purpose of the function is to ensure that the input fields have the necessary length before the submit button can be enabled:
function checkInput ()
{
let usernameLength = document.getElementById('newUsername').value.length;
let nameLength = document.getElementById('newName').value.length;
let emailLength = document.getElementById('newEmail').value.length;
let passwordLength = document.getElementById('newPassword').value.length;
let verifyLength = document.getElementById('verifyPass').value.length;
if (usernameLength >= 5 && nameLength > 0 && emailLength > 0 && passwordLength >= 8 && verifyLength >= 8)
{
document.getElementById('submitButton').disabled = false;
const element = document.querySelector('#submitButton');
if (element.classList.contains('disabled'))
{
element.classList.remove('disabled');
}
}
else
{
document.getElementById('submitButton').disabled = true;
const addElement = document.querySelector('#submitButton');
addElement.classList.add('disabled');
}
}
I also have the following CSS classes that either make the border and shadow of the input field green or red:
.validInput {
border-color: #50c878;
box-shadow: 0 0 5px #50c878;
}
.invalidInput {
border-color: #ff0000;
box-shadow: 0 0 5px #ff0000;
}
My problem is that I would like to add some javascript so that while the user is typing in their information into the form, the code checks to make sure their input matches the patterns that are stated in the input fields. If the input they are putting into the field is valid, I would like for the javascript to add the validInput class to the input field. If the input is invalid I would like to add the invalidInput class to the input field. I have no idea, though, how to go about having JavaScript check if the input follows the pattern.
I would also like to make it to where it checks if the input is valid every time the user has a change event.
Does anyone have any ideas on how to go about doing this?
You can use the addEventListener function with 'change' parameter if you want your verification to run after the user leaves the field, or with 'input' parameter if you want the verification to run each time the user writes something in the text field. This should do it for you:
// If you want the verification to run when the user leaves the input.
document.getElementById('newUsername').addEventListener("change", checkInput);
// If you want the verification to run each time the user changes the input.
document.getElementById('newUsername').addEventListener("input", checkInput);
For the verification part, you can use regex. Create the verification functions first, (checks if the input is valid):
let check_username = (username)=>{
let rx = /^[a-z0-9]{8,40}$/i;
return rx.test(username); // Checks if the username is only made of alphanumeric characters (case insentisive)
}
let check_password = (password)=>{
let special_char = /[0-9!##\$%\^\&*\)\(+=._-]/; // If you want more special characters add them inside the braces at the end (after the '=+._-')
let upper_char = /[a-z]/;
let lower_char = /[A-Z]/;
return special_char.test(password) // Checks if the password contains a special character or a number
&& upper_char.test(password) // Checks if the password contains an upper case letter
&& lower_char.test(password) // Checks if the password contains a lower case letter
&& password.length>=8; // checks the password length
}
let check_email = (email)=>{
let rx = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+$/;
return rx.test(email); // Checks the mail format.
}
Then you can use them like that:
check_username(document.getElementById('newUsername').value)
// This should return true if the username is valid or false if not.
Hope this was helpful. You can close the subject if that's what you are looking for.

Set focus to another field in web form with javascript

I have a web form with two fields:
Email
User name
I want to track user input in the Email field and when it ends with ".com" set focus to another field "User email"
What the best way to do so with JavaScript or jQuery.
This should do the trick. When the last 4 letters of the email input are '.com', the focus is given to the username field.
While this works, please consider the UX issues this may cause. In the comments for your question, Quentin provides a good explanation of why this probably isn't worth implementing.
$('#email').on('input', function() {
email = this.value
if (email.substr(email.length - 4) === '.com')
$('#username').focus()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="email" type="text" placeholder="email">
<input id="username" type="text" placeholder="user name">
as #Quentin mentioned this not a best practice due to these types of emails such as (.com.au)
but if you really know what you are doing then this code does what you want
// select email input
const mail = document.getElementById('mail');
// add input event
mail.addEventListener('input', e => {
// get value
let value = e.target.value.trim();
const regex = /.com$/ig; // matches any string ends with .com
const result = regex.test(value);
// if matches .com at the end then add focus to name input
if (result) {
e.target.nextElementSibling.focus();
}
});
<form>
<input type="text" placeholder="insert your email" id="mail">
<input type="text" placeholder="insert your name" id="name">
</form>

How to validate my password using a regex in Javascript - code attached evaluates to false everytime

I have the code below and it evaluates to false every time and I don't understand why?
Is this a rookie error on my part? (I'm guessing it must be!) I'm typing a password into the password field on my form every time that starts with 1 uppercase letter, followed by 5 lowercase letters and 2 digits.
I want to regex to test for:
At least 1 uppercase letter
At least 1 lower case letter
At least 1 numerical digit
I've tried editing the regex to take away the start and end anchors and have tried lazy and non lazy matching.
I also originally had the function as a function statement outside the anonymous function block and called it from within the anon function.
This is the html for the form:
<form>
<p>Username:</p>
<input
id="userName"
type="text"
required
name="username"
placeholder="Username"
/>
<p>Password:</p>
<input
id="userPassword"
type="password"
required
name="password"
placeholder="Password"
/>
Forgetten Password?
<input id="submit_btn" type="submit" name="submit_btn" />
</form>
//This is the JS
const validateContainer = {
id: [],
username: [],
password: []
};
document.getElementById("submit_btn").addEventListener("click", function() {
let passwordInput = document.getElementById("userPassword").value;
let passwordRegexp = /^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9]).{6,}$/;
let passwordTest = passwordRegexp.test(passwordInput);
if (passwordTest) {
alert("Thank you");
validateContainer.password.push(passwordInput);
} else {
alert("Please re-enter password");
}
console.log(passwordTest);
console.log("Button was clicked");
});
I'm expecting the first branch of the if statement to execute, but keep getting the else alter message and console.log(passwordTest) prints false everytime.

onSubmit button won't load location

I switched from type=click to type=submit so that I can use the Enter key to login. The if/else statements for invalid username/password functions fine. But if I input the correct credentials it wont load the location(different HTML page.)
PS: I'm new to coding in general(only 3 weeks in) Try to explain it so a newbie would know.
Thanks in advance.
<script type="text/javascript">
function check_info(){
var username = document.login.username.value;
var password = document.login.password.value;
if (username=="" || password=="") {
alert("Please fill in all fields")
} else {
if(username=="test") {
if (password=="test") {
location="Random.html"
} else {
alert("Invalid Password")
}
} else {
alert("Invalid Username")
}
}
}
</script>
<form name=login onsubmit="check_info()">
Username:
<input type="text" name="username" id="username"/>
<br>
Password:
<input type="password" name="password" id="password"/>
<br>
<br>
<input type="submit" value="Login"/>
</form>
You need to use .href on location
location.href = "Random.html";
(Also, since you said you were new, be sure to keep your dev console (F12) open when writing JavaScript and testing - you'll catch a lot of errors very early on)
Two things:
1 - Proper way to simulate a clink on a link is to use change the href attribute of location, not location itself. The line below should work:
window.location.href = "Random.html";
2 - As you are redirecting to another page, you have to "suppress" (stop) the natural onsubmit event.
In other words, you have to return false on the onsubmit event, otherwise the redirection (to Random.html) won't have a chance to work because the submit event will kick in (and sedn the user to the action page of the form) before the redirection works.
So change <form name=login onsubmit="check_info()"> to:
<form name=login onsubmit="return check_info()">
And add a return false; to the end of check_info().
The full code should be as follows:
<script type="text/javascript">
function check_info(){
var username = document.login.username.value;
var password = document.login.password.value;
if (username=="" || password=="") {
alert("Please fill in all fields")
} else {
if(username=="test") {
if (password=="test") {
window.location.href = "Random.html"; // ------ CHANGED THIS LINE
} else {
alert("Invalid Password")
}
} else {
alert("Invalid Username")
}
}
return false; // ------------------------ ADDED THIS LINE
}
</script>
And the HTML (only the onsubmit changed):
<form name="login" onsubmit="return check_info()">
Username:
<input type="text" name="username" id="username"/>
<br>
Password:
<input type="password" name="password" id="password"/>
<br>
<br>
<input type="submit" value="Login"/>
</form>
JSFiddle demo here.
The new way of doing this - set a breakpoint at the line
if(username=="test") {
And step through it to find what the problem is.
The old school way of doing this (from back before we had Javascript debuggers) is to alert messages in each of those blocks, and figure out why you step into that block to begin with. It's a lot more cumbersome than the debugger, but sometimes you may need to resort to old school hacks.

Trying to write a jquerying script that uses a submit function to validate two fields

I'm trying to meet the following objectives but having problems with my code to get it to work. Any help would be grateful.
Objective: Add javascript/jQuery code to require a login. Have 2 fields, First Name and Last Name. Validate entry. Must be "Rick" and "James" respectively. Once fields are validated, have a picture appear on the page. When you click the picture, have the page content display. Have at least 2 link buttons with rollover states to change button color and/or text size.
Here is my script:
$(document).ready(function() {
$("#signup").validate({
rules: {
firstName: { required: true },
lastName: { required: true }
}, //end rules
messages: {
firstName: {required: "You must enter a value in this field." },
lastName: {required: "You must enter a value in this field." }
}, // end messages
errorPlacement: function(error, element) {
error.insertAfter(element);
}
}); // end validate
$('#signup').submit(function() {
if (($('#firstname').val() == 'John') && ($('#lastname').val() == 'Taylor'))
{alert('This works!');
$('#pic').show();
$('#main').css("backgorund-image", "url(starwars.jpg)");
}
else { alert('Invalid Name'); }
}); //end submit
$('#pic').click(function() {
$('#button1').show();
$('#button2').show();
}); // end click
}); // end ready
HTML:
<form id="signup">
<div>
<label for="firstName" class="label">First Name</label>
<input name="firstName" type="text" id="firstname" class="required" title="Please type your first name.">
</div>
<div>
<label for="lastName" class="label">Last Name</label>
<input name="lastName" type="test" class="required" id="lastname">
</div>
<div>
<input type="submit" name="submit" id="submit" value="Submit">
</div>
<div>
<img src="sith_ewok.png" id="pic">
<button id="button1">Jedi</button>
<button id="button2">Sith</button>
</div>
</form>
The only error that stands out so far in your code is spelling background-image incorrectly in the submit function.
The one thing that seems likely is that you would see minimal effects from clicking the submit button because of the form automatically posting. That will likely mean that you never see the effects of your script being executed. To fix that, add return false; to the submit processing:
$('#signup').submit(function() {
if (($('#firstname').val() == 'John') && ($('#lastname').val() == 'Taylor'))
{alert('This works!');
$('#pic').show();
$('#main').css("backgorund-image", "url(starwars.jpg)");
}
else { alert('Invalid Name'); }
return false;
}); //end submit
Note that if you are actually going to use this form to do further processing on another page, you might later want to have the submit function allow the page to post in the case that the fields check out. To do that, move the return false; line of code into the else and/or add a return true; as the last line in the main if block.
Make up your mind! Is it "Rick James" or 'John Taylor' ?!
Anyways, the code looks alright except
your should put return false; in $.submit() to prevent page
refreshing
spelling errors on background-color
image and two buttons should be set to display:none at beginning, so the show() function will actually works
Also I do not see your code for changing button color/state anywhere. So I just added some .mouseover and .mouseout events on the buttons. This is normaly can be done with just css such as button:hover {color:red}.
Here is a working demo: http://jsfiddle.net/dUG8Y/
Hope it helps, and may the Force be with you.

Categories

Resources