I am Trying to validate some input for a login form using JavaScript. From what I can see, everything in the script is correct, but it is not working. I'm sure it's a tiny thing that I've missed, any help would be appreciated.
Note: I am unable to use external libraries.
JavaScript code:
<script>
function validateForm() {
var x = document.forms["login"]["username"].value;
var y = document.forms["login"]["password"].value;
if (isNaN(x)) && (y === "") {
alert("Username must be numerical, and password must be entered!");
return false;
} else if (isNaN(x)) && (y !== "") {
alert("Username must be numerical!");
return false;
} else if (Number.isInteger(x) == true) && (y === "") {
alert("Password must be entered!");
return false;
} else {
return true;
}
}
</script>
HTML Code:
<form name="login" method="get">
<input type="text" placeholder="Customer ID" name="username">
<input type="password" placeholder="Password" name="password">
<input type="submit" onclick="return validateForm()" value="Log In" name="button">
<?php if (isset($errormessage)) { echo $errormessage; } ?>
</form>
(I'm very new to web dev, please don't judge too much :p)
In addition to other answers :
this line : var x = document.forms["login"]["username"].value; will store the value of username as a string, even if a numerical value is entered. Now I invite you to test the following line of code :
Number.isInteger('12')
It will return false.
One of the possible solutions would be to use parseInt on x before using it :
var x = parseInt(document.forms["login"]["username"].value);
It will still return NaN if a non int parsable value is given, and transform it to an int if the value is parsable.
Side Note :
parseInt('a') == NaN
parseInt('12') == 12
parseInt('12a') == 12
You were missing brackets around the conditions for if statements.
function validateForm() {
var x = document.forms["login"]["username"].value;
var y = document.forms["login"]["password"].value;
if ((isNaN(x)) && (y === "")) {
alert("Username must be numerical, and password must be entered!");
return false;
} else if ((isNaN(x)) && (y !== "")) {
alert("Username must be numerical!");
return false;
} else if ((Number.isInteger(x) == true) && (y === "")) {
alert("Password must be entered!");
return false;
} else {
return true;
}
}
<form name="login" method="get">
<input type="text" placeholder="Customer ID" name="username">
<input type="password" placeholder="Password" name="password">
<input type="submit" onclick="return validateForm()" value="Log In" name="button">
<?php if (isset($errormessage)) { echo $errormessage; } ?>
</form>
Let me know if you have any questions.
<script>
function validateForm() {
var x = document.forms["login"]["username"].value;
var y = document.forms["login"]["password"].value;
if ( (isNaN(x)) && (y === "")) {
alert("Username must be numerical, and password must be entered!");
return false;
} else if ( (isNaN(x)) && (y !== "")) {
alert("Username must be numerical!");
return false;
} else if ( (Number.isInteger(x) == true) && (y === "")) {
alert("Password must be entered!");
return false;
} else {
return true;
}
}
You have missed some parentheisis in your script please use this code
You've got extra parentheses in your if statement:
if (isNaN(x))<- this is closing the conditional and is not required
Remove that and it should work:
if (isNaN(x) && y === "") {
The else branches also have this issue, the whole if should appear like this:
if (isNaN(x) && y === "") {
alert("Username must be numerical, and password must be entered!");
return false;
} else if (isNaN(x) && y !== "") {
alert("Username must be numerical!");
return false;
} else if (Number.isInteger(x) == true && y === "") {
alert("Password must be entered!");
return false;
} else {
return true;
}
Also, the isNan function can be used from Number (just like isInteger) instead of global, this would make script more consistent :)
Related
I wrote this code for validate password and i need to show user two different alerts.
(pw.length < 8) when this condition executed "Password need minimum 8 characters"
(pw != cpw) "Passwords does not match"
I already tried all if statements but it not gonna help.
<script>
function validatePassword(){
var pw= document.getElementById("txtPassword").value;
var cpw= document.getElementById("txtCPassword").value;
if((pw.length < 8)||(pw != cpw))
{
alert("please enter the correct password")
return false;
Event.preventDefault();
}
return true;
}
</script>
Does anyone know if something...
Use a boolean and two if statements. Return the boolean at the end for true or false.
function validatePassword() {
const pw = document.getElementById("txtPassword").value;
const cpw = document.getElementById("txtCPassword").value;
let isValid = true;
if (pw.length < 8) {
alert('Password is not long enough. Minimum length is 8 characters.');
isValid = false;
}
if(pw !== cpw)) {
alert('Passwords do not match'.);
isValid = false;
}
return isValid;
}
Or have both messages in one alert using an array
function validatePassword() {
const pw = document.getElementById("txtPassword").value;
const cpw = document.getElementById("txtCPassword").value;
const errors = [];
if (pw.length < 8) {
errors.push('Password is not long enough. Minimum length is 8 characters.');
}
if(pw !== cpw)) {
errors.push('Passwords do not match.');
}
if (errors.length) {
alert(errors.join('\n'));
return false;
}
return true;
}
here is most basic version you can use this type of code.
function validatePassword(){
var pw= document.getElementById("txtPassword").value;
var cpw= document.getElementById("txtCPassword").value;
if((pw.length < 8))
{
alert("please enter the correct password")
return false;
} else if((cpw != pw)) {
alert("Passwords does not match")
} else {
alert("Password is correct!")
return true;
}
}
<form id="form">
<input type="text" id="txtPassword">
<input type="text" id="txtCPassword">
<input onclick="event.preventDefault();validatePassword()" type="submit" value="Submit">
</form>
This will do.
<script>
var pw= document.getElementById("txtPassword").value;
var cpw= document.getElementById("txtCPassword").value;
function validatePassword(){
if(pw.length < 8)
{
alert("Password need minimum 8 characters")
}
if(pw != cpw){
alert("Passwords does not match")
}
}
I don't think you need to show 2 alerts. When txtPassword is invalid, users have to retype both passwords whether passwords match or not. There is no point in showing "Passwords does not match" message in that case.
To know how to show 2 alerts, see my second code.
First, here is another solution:
const FORM = document.querySelector('#form');
const PSW = document.querySelector('#txtPassword');
const C_PSW = document.querySelector('#txtCPassword');
FORM.addEventListener('submit', event => {
event.preventDefault();
if (!validatePassword()) return;
console.log('Submitted');
})
function validatePassword() {
let pw = PSW.value;
let cpw = C_PSW.value;
if (pw.length < 8) {
alert('please enter the correct password');
return;
} else if (pw !== cpw) {
alert('Passwords does not match');
return;
}
return true;
}
<form action="" id="form">
<input type="password" id="txtPassword">
<input type="password" id="txtCPassword">
<input type="submit" value="Submit">
</form>
To show 2 alerts:
function validatePassword() {
let pw = PSW.value;
let cpw = C_PSW.value;
if (pw.length < 8) {
alert('please enter the correct password');
if (pw !== cpw) {
alert('Passwords does not match');
}
return;
} else if (pw !== cpw) {
alert('Passwords does not match');
return;
}
return true;
}
So I made a form in a table in html and the javascript code checks till the (creditcard.value.length) after that the code doesn't check anything
<script language="javascript" type="text/javascript">
function ispsd(form) {
var passed = false;
if (form.Fullname.value.length < 4) {
alert("Enter a valid Full Name");
} else if (form.Email.value.indexOf("#") == -1) {
alert("Enter a valid E-mail adress.")
} else if (form.Email.value.indexOf(".") == -1) {
alert("Enter a valid E-mail adress.")
} else if (form.Cardholder.value.length < 3) {
alert("Card Holder name is not Valid.")
} else if (form.Creditcard.value.length != 16) {
alert("Credit card number is not valid.")
} else if (isNan(form.Creditcard.value)) {
alert("Credit card number cannot contain letters.")
} else if (isNan(form.Zip.value)) {
alert("Enter a valid Postal Code.")
} else if ((form.Expyear.value) * 1 < 2021) {
alert("Credit Card has Expired.")
} else if (isNan(form.Expyear.value)) {
alert("Enter a valid Year.")
} else if (form.cvv.value.length != 3) {
alert("Enter a valid CVV.")
} else if (isNan(form.cvv.value)) {
alert("CVV cannot contain letters.")
} else {
passed = true;
}
return passed;
}
</script>
and the thing is when I moved the (form.Expyear.value) * 1 < 2021) above the (form.Creditcard.value.length != 16) the validation worked and when I tried to add all the (else if) above the Credit card check it didn't work
don't know what's the problem
if anyone can help I would be thankful
You can always use console.log() to check what the variable has
function validate(form) {
if (form.Fullname.value.length < 4) {
alert('Enter a valid Full Name');
document.form.Fullname.focus();
return false;
}
if (form.Email.value.indexOf('#') == -1 || form.Email.value.indexOf('.') == -1) {
alert('Enter a valid E-mail adress.');
document.form.Email.focus();
return false;
}
if (form.Cardholder.value.length < 3) {
alert('Card Holder name is not Valid.');
document.form.Cardholder.focus();
return false;
}
console.log(form.Creditcard.value);
if (isNaN(form.Creditcard.value)) {
alert('Credit card number cannot contain letters.');
document.form.Creditcard.focus();
return false;
}
if (form.Creditcard.value.length < 16) {
alert('Credit card number is not valid.');
document.form.Creditcard.focus();
return false;
}
if (isNaN(form.Zip.value)) {
alert('Enter a valid Full Name');
document.form.Zip.focus();
return false;
}
if (isNaN(form.Expyear.value)) {
alert('Enter a valid Year.');
document.form.Expyear.focus();
return false;
}
if (Number(form.Expyear.value) < 2021) {
alert('Enter a valid Year.');
document.form.Expyear.focus();
return false;
}
if (isNaN(form.cvv.value)) {
alert('CVV cannot contain letters.');
document.form.cvv.focus();
return false;
}
if (form.cvv.value.length != 3) {
alert('Enter a valid Year.');
document.form.cvv.focus();
return false;
}
return true;
}
Try to remove the * 1, not sure what's the purpose there
isNaN, and not isNan
I would also handle it differently, what you need is to return true if they pass, rather than identify errors, for example, the demo here below. For example, it will pass your test if you have more than 16 numbers since you're checking x !== 16
function validate() {
var x, text;
// Get the value of the input field with id="numb"
x = document.getElementById("cc").value;
// If x is Not a Number or less than one or greater than 10
if (!isNaN(x) && x.length > 3 && x.length <= 16) {
text = "Input OK";
} else {
text = "Input not valid";
}
document.getElementById("error").innerHTML = text;
}
<p>Please write only numbers, from 4 to 16 maximum characters</p>
<input type="number" id="cc"/><br>
<span id="error"></span><br>
<input type="submit" onclick="validate()" />
Last but not least, this is so verbose and difficult to maintain, I strongly suggest using a library like this one https://www.npmjs.com/package/validator to handle validation, or even jQuery has .validate() useful function for beginner.
I'm having trouble validating if the entered password is same as confirmed password. It doesnt show the text message if it isnt the same or if it is same. It only shows the notice that the password field is empty?
HTML
<div>
<label>Geslo:</label>
<input type="password" id="myInput2" oninput="myFunction2()" name="password" id="koda"><br />
<p id="demo2"></p>
</div>
<div>
<label>Ponovi geslo:</label>
<input type="password" name="repassword" oninput="myFunction3()" id="myInput3"><br />
<p id="demo3"></p>
</div>
JS
function myFunction2() {
var mediumRegex = new RegExp("^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})");
if (m.value === "") {
document.getElementById("demo2").innerHTML = "Prosim vnesite vaš geslo!";
return false;
} else if (mediumRegex.test(m.value) == false) {
document.getElementById("demo2").innerHTML = "Geslo mora vsebovati vsaj eno veliko začetnico in številko!(Min.6 znakov)";
return false;
} else if (mediumRegex.test(m.value) === true) {
document.getElementById("demo2").innerHTML = "";
return true;
}
}
function myFunction3() {
if (n.value === "" || n.value == NULL) {
document.getElementById("demo3").innerHTML = "Prosim ponovno vnesite vaše geslo!";
} else if (n.test(m.value) === false) {
document.getElementById("demo3").innerHTML = "Vaše geslo se ne ujema!";
} else if (n.test(m.value) === true) {
document.getElementById("demo3").innerHTML = "Vaše geslo se ujema!";
}
}
I assume the variables m and n refer the input elements #myInput2 and #myInput3.
When I run your code I got two errors:
1. NULL is not defined
In JavaScript, NULL is null. (I guess it's just a typo tho)
2. n.test is not a function
It seems you are consued with value and element. Since I assume the n refers the input #myInput3, it is a HTMLElement which doesn't have .test() method. .test() is a method of RegExp. For this case, you could compare the two string without RegExp like below.
function myFunction3() {
if (n.value === "" || n.value == null) {
document.getElementById("demo3").innerHTML = "Prosim ponovno vnesite vaše geslo!";
} else if (n.value !== m.value) {
document.getElementById("demo3").innerHTML = "Vaše geslo se ne ujema!";
} else if (n.value === m.value) {
document.getElementById("demo3").innerHTML = "Vaše geslo se ujema!";
}
}
Fiddle: https://jsfiddle.net/dxnmw4v0/
Trivial example just to check if fields are equal.
isPasswordConfirmed = () => {
if($('input.password').val() == $('input.passsword-confirmation').val()) {
return true
}
return false
}
Make sure to classes 'password' and 'password-confirmation' to the inputs
Usage:
if(isPasswordConfirmed()) {
// ... do something
}
else {
//
}
This is what i need help with!
My project needs a If and else statement for the Age part!
and then send the person who has validated correctly to a new page.. I currently have a page but that is just something that is in my USB
also need to explain how its is validating
Please help
!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "")
{
alert("Name must be filled out");
return false;
}
var Age = document.forms["myForm"]["Age"].value;
if (Age == null || Age == "") {
alert("Has to be a number between 1 and 150");
return false;
}
var Email = document.forms["myForm"]["Email"].value;
if (Email == null || Email == "") {
alert("Make sure it is the correct Email format");
return false;
}
var myCheck = document.getElementById("check1").checked;
if (myCheck == false) {
alert("Have to tick box to proceed");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="file:///G:/Welcome.html"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
Age: <input type="text" name="Age">
Email: <input type="text" name="Email">
<br>checkbox: <input type="checkbox" id="check1" name="myCheck"> </br>
<input type="submit" value="click">
</form>
</body>
</html>
You could extend the if clause with the age check.
var age = document.forms["myForm"]["Age"].value;
if (age == "" || age < 1 || age > 150) {
// ^^^^^^^^^^^^^^^^^^^^^^^
alert("Has to be a number between 1 and 150");
return false;
}
I'd parse the value of the form into a number and then I'd check its range:
var age = Number(document.forms["myForm"]["Age"].value) || 0;
if (age < 1 || age > 150) {
alert("Has to be a number between 1 and 150");
return false;
}
Why convert to number and put Number(document.forms["myForm"]["Age"].value) || 0?
The reason is simple: imagine that a malicious user put in your form the value "NaN". If you didn't do this check, the value of age would be NaN and it'd pass your check (NaN < 1 is false and NaN > 150 is false too).
This way, if a user put "NaN" in the form, the guard would transform it into 0, the alert would trigger and the function would return false.
I want to validate a username using Javascript. I have validated if media name is null. Now I want to check special characters are not taken except space.
<input type="text" name="medianame" id="medianame" value="" required="required">
<a class="edit" href="" id="edit" onclick="return chk_val()">Save</a>
<script>
function chk_val() {
if (document.getElementById('medianame').value == "") {
alert("Please enter name");
return false;
}
else {
return false;
}
}
</script>
You can use a regular expression to test whether a string contains only the characters you want to allow:
/^[a-z ]+$/i
...or test for characters that aren't allowed:
/[^a-z ]/i
Use the .test() method in your function as follows:
function chk_val() {
var val = document.getElementById('medianame').value;
if (val === "") {
alert("Please enter name");
return false;
} else if (/[^a-z ]/i.test(val)) {
alert("Please enter only letters or spaces");
return false;
}
return true;
}
function chk_val()
{
var error = false;
var name = document.getElementById('medianame').value;
if (name == "")
error = true;
else if( /^[A-z ]+$/.test(name) == false)
error = true;
if(error)
{
alert("Please enter correct name");
return false;
}
return true;
}
This will check for all the expressions possible. You can filter your needs from this.
var yourExp = /^[a-zA-Z0-9!##\$%\^\&*\)\(+=._-]+$/g;
Then you can match like
var yourStr = document.getElementById('medianame').value;
if( yourStr.match(yourExp) == True ){
alert('Matched');
}