Im trying to have a blur event for when username and password are to short it says username/password must be x long.
For some reason it only works on my username and I have no clue why
HTML
<body>
<div id="page">
<h1>List King</h1>
<h2>New Account</h2>
<form method="post" action="http://www.example.org/register">
<label for="username">Create a username: </label>
<input type="text" id="username" />
<div id="feedback"></div>
<label for="password1">Create a password: </label>
<input type="password" id="password"/>
<div id="feedback"></div>
<input type="submit" value="sign up" />
</form>
</div>
<script src="event-listener.js"></script>
</body>
javascript
function checkUsername() {
var elMsg = document.getElementById('feedback');
if (this.value.length < 5) {
elMsg.textContent = 'Username must be 5 characters or more';
} else {
elMsg.textContent = '';
}
}
var elUsername = document.getElementById('username');
elUsername.addEventListener('blur', checkUsername, false);
function checkPassword() {
var elMsg = document.getElementId('feedback');
if (this.value.length < 6){
elMsg.textContent = 'Password must be 6 characters or more';
} else {
elMsg.textContent = ' ';
}
}
var elPassword = doucment.getElementById('password');
elPassword.addEventListener('blur', checkPassword, false);
Created a plunkr example here< https://plnkr.co/edit/MBkFQSEjbKIAFPDOFUTW?p=preview >. You have few spelling mistakes in your code and used the same id to show the message. I used html5 tags for blur event instead of event listeners.
function checkUsername() {
var usernameLength=document.getElementById('username').value.length;
var elMsg = document.getElementById('feedback1');
if (usernameLength < 5) {
elMsg.textContent = 'Username must be 5 characters or more';
} else {
elMsg.textContent = 'good';
}
}
function checkPassword() {
var elPassword = document.getElementById('password');
var elMsg = document.getElementById('feedback2');
if (elPassword.value.length < 6){
elMsg.textContent = 'Password must be 6 characters or more';
} else {
elMsg.textContent = ' ';
}
}
</head>
<body>
<div id="page">
<h1>List King</h1>
<h2>New Account</h2>
<form method="post" action="http://www.example.org/register">
<label for="username">Create a username: </label>
<input type="text" id="username" />
<div id="feedback"></div>
<label for="password1">Create a password: </label>
<input type="password" id="password"/> <div id="feedback1"></div>
<input type="submit" value="sign up" />
</form>
</div>
<script src="event-listener.js"></script>
</body>
</html>
function checkUsername() { // Declare function
var elMsg = document.getElementById('feedback'); // Get feedback element
if (this.value.length < 5) { // If username too short
elMsg.textContent = 'Username must be 5 characters or more'; // Set msg
} else { // Otherwise
elMsg.textContent = ''; // Clear msg
}
}
var elUsername = document.getElementById('username'); // Get username input
// When it loses focus call checkUsername()
elUsername.addEventListener('blur', checkUsername, false);
function CheckPassword() { // Declare function
var elMsg = document.getElementById('feedback1'); // Get feedback element
if (this.value.length < 6) { // If username too short
elMsg.textContent = 'Password must be 6 characters or more'; // Set msg
} else { // Otherwise
elMsg.textContent = ''; // Clear msg
}
}var elPassword = document.getElementById('password'); // Get username input
elPassword.addEventListener('blur', CheckPassword, false);
Related
I have an issue while submitting a form its giving me error that >validateform()is not defined
before it was working.
It is loan application in which I have to send an email once user submit form with correct details and also generate random 4 digit no which will be in email which user will receive
<script src="https://smtpjs.com/v3/smtp.js">
## Heading ##
function validateForm() {
let name = document.forms["myForm"]["fullName"].value;
let email = document.forms["myForm"]["email"].value;
let pan = document.forms["myForm"]["pan"].value;
let lamount = document.forms["myForm"]["flamnt"].value;
let regName = /\d+$/g;
let regEmail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/g;
let regPan = /^([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}?$/;
//captcha validation
let input_val = document.getElementById('input_val');
let num1 = document.getElementById('num1');
let num2 = document.getElementById('num2');
const mybtn = document.getElementById('btn');
//returns a random integer from 0to9
num1.innerText = Math.floor(Math.random() * 10);
num2.innerText = Math.floor(Math.random() * 10);
let number1 = num1.innerText;
let number2 = num2.innerText;
enter code here
mybtn.addEventListener("click", () => {
//
let sum_result = parseInt(number1) + parseInt(number2);
let res = parseInt(input_val.value);
if (res == sum_result) {
alert("correct");
}
else {
alert("Incorrect")
}
window.location.reload();
});
if (name == "" || regName.test(name)) {
alert("Name must be filled out");
return false;
}
if (email == "" || !regEmail.test(email)) {
alert("Please enter a valid e-mail address.");
return false;
}
if (pan == "" || !regPan.test(pan)) {
alert("Please enter a valid PAN no.");
return false;
}
//OTP generation
const generateOtp = () =>{
let otp = "";
for(let i=0 ; i < 4 ; i++){
otp += Math.floor(Math.random() * 10);
}
//if we write return otp directly then this will return otp in string
return Number(otp); //this will return otp as number.
};
console.log("OTP:", generateOtp());
}
//sending an email
// function sendEmail() {
// Email.send({
// Host: "smtp.gmail.com",
// Username: "...#gmail.com",
// Password: "....",
// To: document.getElementById("email").value,
// From: "....#gmail.com",
// Subject: "Thank you for Inquiry",
// Body: "Well that was easy!!",
// })
// .then(function (message) {
// alert("mail sent successfully")
// });
// }
</script>
</head>
<body>
<div class="form-container">
<h1>Loan Application Form</h1>
<form name="myForm" method="post" action="thankyou.html" onsubmit="validateForm();">
<div class="formdesign" id="name">
Full Name:<input type="text" class="form-control" placeholder="Enter your fullname" name="fullName"><span
class="formerror"></span>
</div>
<div class="formdesign" id="email">
Email:<input type="email" class="form-control" placeholder="Enter email" name="email"><span
class="formerror"></span>
</div>
<div class="formdesign" id="panno">
PAN No:<input type="text" class="form-control" placeholder="Like BBHPM5672K" name="pan" maxlength="10"><span
class="formerror"></span>
</div>
<div class="formdesign" id="lamount">
Loan Amount:<input type="number" class="form-control" placeholder="Enter loan amount" name="flamnt"><span
class="formerror"></span>
</div>
<div class="formdesign">
Enter Captcha:<input type="text" placeholder="enter captcha" class="form-control" id="input_val" />
<p id="operation"><span id="num1">1</span> + <span id="num2">2</span></p>
<button id="bttn" class="captcha-refresh"><i class="fa fa-refresh"></i>Refresh</button>
</div>
<input id="btn" class="button" type="submit" value="Submit">
<input class="button" type="reset" value="Reset">
</form>
You have many issues
You do not have a closing </script> for your <script src="https://smtpjs.com/v3/smtp.js"> and a starting <script> for your code.
Please try to use the snippet editor [<>] and remove the "enter code here" and ## Heading ##
You need to use the submit event and e.preventDefault is stopping the submit. I changed name="myForm" to id="myForm", forms do not need names
You are adding event listeners in the validation.
You were missing the refresh function
Here is what I believe you need
const generateOtp = () => {
let otp = "";
for (let i = 0; i < 4; i++) {
otp += Math.floor(Math.random() * 10);
}
//if we write return otp directly then this will return otp in string
return Number(otp); //this will return otp as number.
};
document.getElementById('bttn').addEventListener("click", e => {
e.preventDefault();
let num1 = document.getElementById('num1');
let num2 = document.getElementById('num2');
//returns a random integer from 0to9
num1.innerText = Math.floor(Math.random() * 10);
num2.innerText = Math.floor(Math.random() * 10);
})
document.getElementById("myForm").addEventListener("submit", (e) => {
const form = e.target;
let name = form["fullName"].value;
let email = form["email"].value;
let pan = form["pan"].value;
let lamount = form["flamnt"].value;
let regName = /\d+$/g;
let regEmail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/g;
let regPan = /^([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}?$/;
//captcha validation
let input_val = document.getElementById('input_val');
let num1 = document.getElementById('num1');
let num2 = document.getElementById('num2');
let number1 = num1.innerText;
let number2 = num2.innerText;
let errors = [];
let sum_result = parseInt(number1) + parseInt(number2);
let res = parseInt(input_val.value);
if (res != sum_result) errors.push("Sum not correct");
if (name == "" || regName.test(name)) errors.push("Name must be filled out");
if (email == "" || !regEmail.test(email)) errors.push("Please enter a valid e-mail address.");
if (pan == "" || !regPan.test(pan)) errors.push("Please enter a valid PAN no.");
if (errors) {
alert(errors.join("\n"));
e.preventDefault();
return
}
//OTP generation
console.log("OTP:", generateOtp()); // not sure what you want with this
// sendEmail()
})
//sending an email
// function sendEmail() {
// Email.send({
// Host: "smtp.gmail.com",
// Username: "...#gmail.com",
// Password: "...",
// To: document.getElementById("email").value,
// From: "...#gmail.com",
// Subject: "Thank you for Inquiry",
// Body: "Well that was easy!!",
// })
// .then(function (message) {
// alert("mail sent successfully")
// });
// }
<script src="https://smtpjs.com/v3/smtp.js"></script>
<div class="form-container">
<h1>Loan Application Form</h1>
<form id="myForm" method="post" action="thankyou.html">
<div class="formdesign" id="name">
Full Name:<input type="text" class="form-control" placeholder="Enter your fullname" name="fullName"><span class="formerror"></span>
</div>
<div class="formdesign" id="email">
Email:<input type="email" class="form-control" placeholder="Enter email" name="email"><span class="formerror"></span>
</div>
<div class="formdesign" id="panno">
PAN No:<input type="text" class="form-control" placeholder="Like BBHPM5672K" name="pan" maxlength="10"><span class="formerror"></span>
</div>
<div class="formdesign" id="lamount">
Loan Amount:<input type="number" class="form-control" placeholder="Enter loan amount" name="flamnt"><span class="formerror"></span>
</div>
<div class="formdesign">
Enter Captcha:<input type="text" placeholder="enter captcha" class="form-control" id="input_val" />
<p id="operation"><span id="num1">1</span> + <span id="num2">2</span></p>
<button id="bttn" class="captcha-refresh"><i class="fa fa-refresh"></i>Refresh</button>
</div>
<input id="btn" class="button" type="submit" value="Submit">
<input class="button" type="reset" value="Reset">
</form>
As stated in the title, I have a function which should display an error message, but doesn't. I get an error:
Cannot set property 'textContent' of null
So basically, when a person clicks a check button, the input fields get a required "status". Once that happens, and error should appear underneath the input fields stating that they are required and should be filled out.
This does not happen (Cannot set property 'textContent' of null).
Any help would be welcome.
innerHTML of null error: pnameError.innerHTML = '';
textContent of null error: pnameError.textContent = 'You need to insert your name.';
JS
let pname = document.getElementById("popupfname");
let pnameError = document.querySelector("#popupfname + span#pf");
let pemail = document.getElementById("popupemail");
let pemailError = document.querySelector("#popupemail + span#pe");
var adverts = document.querySelector("input[name=advertsM]");
adverts.addEventListener('change', function() {
if (this.checked) {
console.log("CHECKED");
document.getElementById("popupfname").required = true;
document.getElementById("popupemail").required = true;
/* Prikaži error msg iz prve */
showNameError();
showEmailError();
} else {
console.log("NOT");
document.getElementById("popupfname").required = false;
document.getElementById("popupemail").required = false;
popfn();
popem();
}
});
function popfn (event) {
if (pname.validity.valid) {
pnameError.innerHTML = '';
pnameError.className = 'error'; //
} else {
showNameError();
}
};
function popem (event) {
if (pemail.validity.valid) {
pemailError.innerHTML = '';
pemailError.className = 'error';
} else {
showEmailError();
}
};
function showNameError() {
if (pname.validity.valueMissing) {
pnameError.textContent = 'You need to insert your name.';
} else if (pname.validity.typeMismatch) {
pnameError.textContent = 'Entered value must a name.';
} else if (pname.validity.tooShort) {
pnameError.textContent = 'Entered name must be atleast 3 characters long.';
}
pname.className = 'error active';
}
function showEmailError() {
if (pemail.validity.valueMissing) {
pemailError.textContent = 'You need to insert your e-mail address.';
} else if (pemail.validity.typeMismatch) {
pemailError.textContent = 'Entered value must be a valid e-mail address.';
} else if (pemail.validity.tooShort) {
pemailError.textContent = 'Entered e-mail address must be atleast 6 characters long.';
}
pemail.className = 'error active';
}
HTML
<form accept-charset="UTF-8" name="popupform" onsubmit="return false;" method="post" id="popupform">
<div id="adv-t"></div><br />
<label class="mlist">
<input type="checkbox" name="advertsM" id="advertsM" value="Yes">
<span id="adv-c"></span>
<br />
</label><br />
<input type="text" pattern="[A-Za-z][^0-9]{2,25}" name="popupfname" id="popupfname" placeholder="Janez"autocorrect="off" autocapitalize="off" /><br />
<span id="pf" class="error pfn" aria-live="polite"></span><br />
<input type="email" name="popupemail" id="popupemail" autocorrect="off" autocapitalize="off" maxlength="45" placeholder="moj#email.si"/><br />
<span id="pe" class="error pem" aria-live="polite"></span><br /><br />
<div id="small">
</div>
<hr style="margin-top: -6px;">
<button id="allow">
<span id="a"></span>
</button>
<button id="deny" onclick="deny()">
<span id="d"></span>
</button>
</form>
The problem is the next element to input is br, not a span
change
let pnameError = document.querySelector("#popupfname + span#pf")
...
let pemailError = document.querySelector("#popupemail + span#pe");
to
let pnameError = document.querySelector("#popupfname + br + span#pf")`
...
let pemailError = document.querySelector("#popupemail + br + span#pe");
Working example:
let pname = document.getElementById("popupfname");
let pnameError = document.querySelector("#popupfname + br + span#pf"); // <-- here ou had an error, because the next element to #popupfname is br, but not the span id="pf"
let pemail = document.getElementById("popupemail");
let pemailError = document.querySelector("#popupemail + br + span#pe"); // <-- here ou had an error, because the next element to #popupemail is br, but not the span id="pe"
var adverts = document.querySelector("input[name=advertsM]");
adverts.addEventListener( 'change', function() {
if(this.checked) {
console.log("CHECKED");
document.getElementById("popupfname").required = true;
document.getElementById("popupemail").required = true;
/* Prikaži error msg iz prve */
showNameError();
showEmailError();
} else {
console.log("NOT");
document.getElementById("popupfname").required = false;
document.getElementById("popupemail").required = false;
popfn();
popem();
}
});
function popfn (event) {
if (pname.validity.valid) {
pnameError.innerHTML = '';
pnameError.className = 'error'; //
} else {
showNameError();
}
};
function popem (event) {
if (pemail.validity.valid) {
pemailError.innerHTML = '';
pemailError.className = 'error';
} else {
showEmailError();
}
};
function showNameError() {
if(pname.validity.valueMissing){
pnameError.textContent = 'You need to insert your name.';
}else if(pname.validity.typeMismatch){
pnameError.textContent = 'Entered value must a name.';
}else if(pname.validity.tooShort){
pnameError.textContent = 'Entered name must be atleast 3 characters long.';
}
pname.className = 'error active';
}
function showEmailError() {
if(pemail.validity.valueMissing){
pemailError.textContent = 'You need to insert your e-mail address.';
}else if(pemail.validity.typeMismatch){
pemailError.textContent = 'Entered value must be a valid e-mail address.';
}else if(pemail.validity.tooShort){
pemailError.textContent = 'Entered e-mail address must be atleast 6 characters long.';
}
pemail.className = 'error active';
}
<form accept-charset="UTF-8" name="popupform" onsubmit="return false;" method="post" id="popupform">
<div id="adv-t"></div><br />
<label class="mlist">
<input type="checkbox" name="advertsM" id="advertsM" value="Yes">
<span id="adv-c"></span>
<br />
</label><br />
<input type="text" pattern="[A-Za-z][^0-9]{2,25}" name="popupfname" id="popupfname" placeholder="Janez"autocorrect="off" autocapitalize="off" /><br />
<span id="pf" class="error pfn" aria-live="polite"></span><br />
<input type="email" name="popupemail" id="popupemail" autocorrect="off" autocapitalize="off" maxlength="45" placeholder="moj#email.si"/><br />
<span id="pe" class="error pem" aria-live="polite"></span><br /><br />
<div id="small">
</div>
<hr style="margin-top: -6px;">
<button id="allow">
<span id="a"></span>
</button>
<button id="deny" onclick="deny()">
<span id="d"></span>
</button>
</form>
I would like to know how to validate a form when I use the onblur handler and the onsubmit handler at the same time. I've tried to do it and it goes straight to the submit page without displaying an error message.
Because I also have radio buttons and checkboxes, how do I validate these if the user didn't click the radio button and exclude the checkbox from validation.
Thank You
function IsNotBlank(tf, tfHelp) {
var value = tf.value;
if (value == " ") {
tf.className = "invalid ";
tfHelp.innerHTML = "This field can 't be blank.";
return false;
} else {
tf.className = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckLetters(tf, tfHelp) {
//check empty field from previous function.
var NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false) {
return false;
}
//assign field value
var value = tf.value;
//check if there is numbers.
var regex = new RegExp(/^[A-Za-z]{5,18}$/);
var testResult = regex.test(value);
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Use letters only and lengths must be between 5 and 18 characters.";
return false;
} else {
tf.className = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckPhNumber(tf, tfHelp) {
//check empty field
var NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false)
return false;
var value = tf.value;
//validate phone number.
var regex = /^\d{8,10}$/;
var testResult = regex.test(value);
//logic
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Please enter a valid phone number.";
return false;
} else {
tf.ClassName = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckEmail(tf, tfHelp) {
//check empty field
NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false) {
return false;
}
var value = tf.value;
//validate email address
var regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var testResult = regex.test(value);
//logic
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Please enter a valid email address.";
return false;
} else {
tf.className = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckPostCode(tf, tfHelp) {
//check empty field
var NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false)
return false;
var value = tf.value;
//validate postcode.
var regex = /^\d{4}$/;
var testResult = regex.test(value);
//logic
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Please enter a 4 digit post code.";
return false;
} else {
tf.ClassName = "valid";
tfHelp.innerHTML = "";
return false;
}
}
function ValidateForm(form) {
var formCheck = true;
for (var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
//alert(form.elements[i]);
if (e.onblur) {
// alert(e.onblur());
formCheck = e.onblur() && formCheck;
}
}
return formCheck;
}
function ResetForm(form) {
//select input elements and change color back to default
var arrayInputs = document.getElementsByTagName("input");
for (var i = 0; i < arrayInputs.length; i++) {
arrayInputs[i].className = "valid";
}
//clear text on span elements
var arraySpans = document.getElementsByTagName('span ');
for (var i = 0; i < arraySpans.length; i++) {
arraySpans[i].innerHTML = "";
}
}
<form action="submit.html" onreset="ResetForm()" onsubmit="ValidateForm(this);">
<div>
<label for="fname" class="label">First Name:</label>
<input class="valid" type="text" id="txtFname" onblur="return CheckLetters(this, txtFnameHelp);" />
<span id="txtFnameHelp"></span>
</div>
<div class="one">
<label for="lname" class="label">Last Name:</label>
<input class="valid" name="lname" id="txtLname" type="text" onblur="return CheckLetters(this, txtLnameHelp);" />
<span id="txtLnameHelp"></span>
</div>
<div class="one">
<label class="label" for="phone">Phone Number:</label>
<input class="one" id="txtPhone" type="text" onblur="CheckPhNumber(this, txtPhoneHelp);"><br>
<span id="txtPhoneHelp"></span>
</div>
<div class="one">
<label for="email" class="label">Email Address:</label>
<input class="valid" id="txtEmail" type="text" onblur="CheckEmail(this, txtEmailHelp)">
<span id="txtEmailHelp"></span><br>
</div>
<div class="one">
<label class="label">Post Code:</label>
<input id="txtPostcode" type="text" onblur="CheckPostCode(this, txtPostCodeHelp);"> <br>
<span id="txtPostCodeHelp"></span>
</div>
<br>
<div>
<label>Prefered Contact Method</label><br>
</div>
<div class="one">
</--<input type="radio" name="contact" value="email">Email
</-- <input type="radio" name="contact" value="phone">Phone
</div>
<br>
<div class="one">
<label>Your Message:</label><br />
<textarea id="txtMessage" rows="8" cols="40" onblur="IsNotBlank(this, txtMessageHelp)">Your Message</textarea>
<span id="txtMessageHelp"></span>
<br><br>
</div>
</--<input class="one" type="checkbox" name="newsletter" value="subscribe">I would like to subscribe to the newsletter <br>
<div>
<input class="one" type="submit" value="Send">
<input class="one " type="Reset " value="Clear">
<br><br>
</div>
</form>
Note that these type of JavaScript code can only be debugged using Microsoft Visual Studio for some reason and would not work on using legacy text editors.
You can use below concept to perform the both action and use window.addEventListener('DOMContentLoaded'function(e) {}) to check the validation
var error_user_name = false;
function checkpw(ele, e){
var user_name = document.forms["joinform"]["user_name"].value;
if (user_name == null || user_name == "") {
text = "UserName : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_name = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_name = true;
}
}
function submitall(ele, e) {
checkpw();
if(error_user_name == false) {
e.preventDefault();
} else {
console.log('form submitted');
}
}
window.addEventListener('DOMContentLoaded', function(e) { document.getElementById('user_name').addEventListener('blur', function(e) {
checkpw(this, e);
setTimeout(function() {
if (document.activeElement.id == 'join') {
document.activeElement.click();
}
}, 10);
}, false);
document.getElementById('joinform').addEventListener('submit', function(e) {
submitall(this, e);
}, false);
});
<form id="joinform" method="post" name="joinform" action="#hello">
<h2>Join</h2>
<input type="text" name="user_name" id="user_name" placeholder="User_Name"/>
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>
I have a submit form that users are using to register:
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>" name="form" onSubmit="return validate(this);">
<div class="form-group">
<input type="text" id="name" name="name" class="inputs" /><br />
<input type="text" id="email" name="email" class="inputs" /><br />
<input type="password" id="password" name="password" class="inputs" />
</div>
<input type="submit" class="btn1" name="register" value="Register" />
</form>
The JS code is checking if the data is entered correctly. If the user enters incorrect date the JS code is showing a message. Now I want to show a message when the data is entered correctly. I tried to add a row like if (errors.length < 0) but this didn't work. The JS code sends me the message for the "correct input" and the message "Dont use symbols...\n".
How can I make this working?
Here is my JS code:
<script type="text/javascript">
var ck_name = /[A-Za-z0-9. ]{3,25}$/;
var ck_email = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var ck_password = /^[A-Za-z0-9!##$%^&*()_]{6,20}$/;
function validate(form)
{
var name = form.name.value;
var email = form.email.value;
var password = form.password.value;
var errors = [];
if (!ck_name.test(name))
{
errors[errors.length] = "Name error! .";
}
if (!ck_email.test(email))
{
errors[errors.length] = "Email error! .";
}
if (!ck_password.test(password))
{
errors[errors.length] = "Password error!";
}
if (errors.length > 0)
{
reportErrors(errors);
return false;
}
return true;
}
function reportErrors(errors)
{
var msg = "Dont use symbols...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>
Errors.length never won't be minor of 0. You must use equal (==). This works! :-)
UPDATE
if (errors.length == 0) {
alert('Correct input');
}
That would be before the return true statement and after the if (errors.length > 0).
Hi there I am really stuck on this and since I am a javscript beginner this boggles my mind.
Is there someone who knows how to write the following javascript form validation?
I am sure that it is very simple, but I can not figure this one out to save my life.
Thank you for you sharing your knowledge.
I need to write WITHOUT jquery the following form validation. Whenever an error is encountered, prevent the form from being submitted. I need to use the window.onload function to assign a validation callback function. There are 4 inputs which get validated by the javascript code. Also the javascript needs to be in its own file.
Validation Rules are as follow:
INPUT: Username; Required (yes); Validation (Must be 5-10 characters long).
INPUT: Email; Required (yes); Validation (Must have an # sign, must have a period).
INPUT: Street name; Required (no); Validation (Must start with a number).
INPUT: Year of birth; Required (yes); Validation (must be numeric).
My code looks as follow:
HTML:
<!DOCTYPE html>
<html>
<head>
<script defer="defer" type="text/javascript" src="form.js"></script>
</head>
<body>
<form action="fake.php">
Username*: <input type="text" class="required" name="u"/><br/>
Email*: <input type="text" class="required" name="p"/><br/>
Street address: <input type="text" class="numeric" name="s"/><br/>
Year of birth*: <input type="text" class="required numeric" name="b"/><br/>
<input type="submit"/><br/>
</form>
</body>
</html>
JS
document.forms[0].elements[0].focus();
document.forms[0].onsubmit=function(){
for(var i = 0; i < document.forms[0].elements.length; i++){
var el = document.forms[0].elements[i];
if((el.className.indexOf("required") != -1) &&
(el.value == "")){
alert("missing required field");
el.focus();
el.style.backgroundColor="yellow";
return false;
}
if((el.className.indexOf("numeric") != -1) &&
(isNaN(el.value))){
alert(el.value + " is not a number");
el.focus();
el.style.backgroundColor="pink";
return false;
}
}
}
without changing much of your code ... updated your code for other validation like length (needs a class verifylength to validate length) and so on....
try this
HTML
<form action="fake.php">Username*:
<input type="text" class="required verifylength" name="u" />
<br/>Email*:
<input type="text" class="required email" name="p" />
<br/>Street address:
<input type="text" class="numeric" name="s" />
<br/>Year of birth*:
<input type="text" class="required numeric" name="b" />
<br/>
<input type="submit" />
<br/>
</form>
JAVASCRIPT
document.forms[0].elements[0].focus();
document.forms[0].onsubmit = function () {
for (var i = 0; i < document.forms[0].elements.length; i++) {
var el = document.forms[0].elements[i];
if ((el.className.indexOf("required") != -1) && (el.value == "")) {
alert("missing required field");
el.focus();
el.style.backgroundColor = "yellow";
return false;
} else {
if (el.className.indexOf("verifylength") != -1) {
if (el.value.length < 5 || el.value.length > 10) {
alert("'" + el.value + "' must be 5-10 charater long");
el.focus();
el.style.backgroundColor = "pink";
return false;
}
}
}
if (el.className.indexOf("email") != -1) {
var regEx = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
var emailTest = regEx.test(el.value);
if (!emailTest) {
alert("email not valid");
el.focus();
el.style.backgroundColor = "yellow";
return false;
}
};
if ((el.className.indexOf("numeric") != -1) && (isNaN(el.value))) {
alert(el.value + " is not a number");
el.focus();
el.style.backgroundColor = "pink";
return false;
}
}
}
working fiddle
something alongs the lines of...
//username 5-10 chars
var uVal = document.getElementsByTagName("u").value;
if (uVal.length < 5 || uVal.length > 10) return false;
//email needs # and .
var eVal = document.getElementsByTagName("p").value;
if !(eVal.match('/.*#.*\./g')) return false;
//street starts w/ num
var sVal = document.getElementsByTagName("s").value;
if !(sVal.match('/^[0-9]/g')) return false;
i think the regex is off + untested :)
Here is your javascript validation object in work. Hope you can make some modification according to your need.
Style
<style>
.valid {border: #0C0 solid 1px;}
.invalid {border: #F00 solid 1px;}
</style>
HTML Form
<div>
<form id="ourForm">
<label>First Name</label><input type="text" name="firstname" id="firstname" class="" /><br />
<label>Last Name</label><input type="text" name="lastname" id="lastname" class="" /><br />
<label>Username</label><input type="text" name="username" id="username" class="" /><br />
<label>Email</label><input type="text" name="email" id="email" class="" /><br />
<input type="submit" value="submit" class="" />
</form>
</div>
Call script before closing tag
<script src="form_validation_object.js"></script>
form_validation_object.js
/*
to: dom object
type: type of event
fn: function to run when the event is called
*/
function addEvent(to, type, fn) {
if (document.addEventListener) { // FF/Chrome etc and Latest version of IE9+
to.addEventListener(type, fn, false);
} else if (document.attachEvent) { //Old versions of IE. The attachEvent method has been deprecated and samples have been removed.
to.attachEvent('on' + type, fn);
} else { // IE5
to['on' + type] = fn;
}
}
// Your window load event call
addEvent(window, 'load', function() {
/* form validation object */
var Form = {
validClass: 'valid',
inValidClass: 'invalid',
fname: {
minLength: 1,
maxLength: 8,
fieldName: 'First Name'
},
lname: {
minLength: 1,
maxLength: 12,
fieldName: 'Last Name'
},
username: {
minLength: 5,
maxLength: 10,
fieldName: 'Username'
},
validateLength: function(formElm, type) {
//console.log('string = ' + formElm.value);
//console.log('string length = ' + formElm.value.length);
//console.log('max length=' + type.maxLength);
//console.log(Form.validClass);
if (formElm.value.length > type.maxLength || formElm.value.length < type.minLength) {
//console.log('invalid');
//alert(formElm.className);
if (formElm.className.indexOf(Form.inValidClass) == -1) {
if (formElm.className.indexOf(Form.validClass) != -1) {
formElm.className = formElm.className.replace(Form.validClass, Form.inValidClass);
} else {
formElm.className = Form.inValidClass;
}
}
//alert(formElm.className);
return false;
} else {
//console.log('valid');
//alert(formElm.className.indexOf(Form.validClass));
if (formElm.className.indexOf("\\b" + Form.validClass + "\\b") == -1) { // regex boundary to match whole word only http://www.regular-expressions.info/wordboundaries.html
//formElm.className += ' ' + Form.validClass;
//alert(formElm.className);
if (formElm.className.indexOf(Form.inValidClass) != -1)
formElm.className = formElm.className.replace(Form.inValidClass, Form.validClass);
else
formElm.className = Form.validClass;
}
return true;
}
},
validateEmail: function(formElm) {
var regEx = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
var emailTest = regEx.test(formElm.value);
if (emailTest) {
if (formElm.className.indexOf(Form.validClass) == -1) {
formElm.className = Form.validClass;
}
return true;
} else {
formElm.className = Form.inValidClass;
return false;
}
},
getSubmit: function(formID) {
var inputs = document.getElementById(formID).getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'submit') {
return inputs[i];
}
}
return false;
}
}
/* call validation object */
var ourForm = document.getElementById('ourForm');
var submit_button = Form.getSubmit('ourForm');
submit_button.disabled = 'disabled';
function checkForm() {
var inputs = ourForm.getElementsByTagName('input');
if (Form.validateLength(inputs[0], Form.fname)) {
if (Form.validateLength(inputs[1], Form.lname)) {
if (Form.validateLength(inputs[2], Form.username)) {
if (Form.validateEmail(inputs[3])) {
submit_button.disabled = false;
return true;
}
}
}
}
submit_button.disabled = 'disabled';
return false;
}
checkForm();
addEvent(ourForm, 'keyup', checkForm);
addEvent(ourForm, 'submit', checkForm);
});
Working example at JSBin
http://jsbin.com/ezujog/1