validation is not done on submit button click - javascript

<script>
function ValidateEmail(){
var emailID = document.getElementById("email").value;
var email = document.getElementById("email");
var emailRegexp=/^[a-z]+\w+([\.-]?\w+)*#[a-z]+\w+([\.-]?\w+)*(\.[a-z]{2,3})+$/i;
if ((emailID==null)||(emailID=="")){
// alert("Please Enter your Email ID");
email.style.borderColor="red";
document.getElementById("err").innerHTML = "Please Enter your Email ID";
emailID.focus();
return false;
}
else
if (!emailRegexp.test(emailID)){
//alert("Please Enter valid Email ID");
email.style.borderColor="red";
document.getElementById("err").innerHTML = "Please Enter valid Email ID";
emailID.focus();
return false;
}
else
{
email.style.borderColor="#e1e1e1";
document.getElementById("err").innerHTML ="";
return true;
}
}
function validUsername()
{
var error = "";
var illegalChars = /\W/; // No special Characters allowed
var fd =document.getElementById("name");
if (fd.value == "" || fd.value == null)
{
fd.style.borderColor = 'Red';
document.getElementById("UserErr").innerHTML = " Field is left Blank.\n";
return false;
}
else if ((fd.value.length < 5) || (fd.value.length > 20)) // Number of Character entered is checked
{
fd.style.borderColor = 'Red';
document.getElementById("UserErr").innerHTML = "Username is should be in a range of 5 and 15..\n";
return false;
}
else if (illegalChars.test(fd.value)) // check for illegal characters
{
fd.style.borderColor = 'Red';
document.getElementById("UserErr").innerHTML = "Illegal Characters not allowed\n";
return false;
}
else
{
fd.style.borderColor = '#e1e1e1';
document.getElementById("UserErr").innerHTML = "";
return true;
}
}
function validPassword()
{
var error = "";
var password=document.getElementById("pass");
var passError=document.getElementById("PassErr");
var illegalChars = /[\W_]/; // Numbers and letter only
var checkPass=/\w*[a-z]+\d+\w*/i;
if (password.value == "" || password.value == null)
{
password.style.borderColor = 'Red';
passError.innerHTML = "Field Cannot be blank.\n";
return false;
}
else if ((password.value.length < 8) || (password.value.length > 20)) // Checks length of the password
{
password.style.borderColor = 'Red';
passError.innerHTML = "Length should be in Range of 8 to 20. \n";
return false;
}
else if (illegalChars.test(password.value))
{
password.style.borderColor = 'Red';
passError.innerHTML = "Illegal characters not allowed.\n";
return false;
}
else if (!checkPass.test(password.value)) // Checks for numeric value in entered password
{
password.style.borderColor = 'Red';
passError.innerHTML = "Atleast one Numeric value Required ";
return false;
}
else
{
password.style.borderColor = '#e1e1e1';
passError.innerHTML = "";
return true;
}
}
function validateOnSubmit()
{
if(ValidateEmail() && validUsername() && validPassword());
return true;
return false;
}
</script>
<form method="post" name="form">
<!--<input type="text" name="email" id="email" placeholder="Your Email" onblur="return ValidateEmail()"/><span id="err"></span></td>-->
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="uname" id="name" placeholder="User Name" onblur="validUsername()"/><span id="UserErr" style="color:red"></span></td>
</tr>
<tr>
<td><input type="text" name="email" id="email" placeholder="Your Email" onblur="ValidateEmail()"/><span id="err"></span></td>
</tr>
<tr>
<td><input type="password" name="pass" id="pass" placeholder="Your Password" onblur="validPassword()" /><span id="PassErr" style="color:red"></span></td>
</tr>
<tr>
<td><button type="submit" onsubmit="return validateOnSubmit()" name="btn-signup">Sign Me Up</button></td>
</tr>
</table>
</form>
I have created registration form and create validation in JavaScript for input fields.
onBlur validation is done, and works fine.
But when I click on the 'Sign Me Up' button, validation is not done and data is inserted into the database. Please I need help.

submit events fire on forms, not submit buttons. Move the onsubmit attribute to the <form> start tag.

"emailID.focus(); " is wrong is in ValidateEmail() function. instead of it
"email.focus(); is right.
Now it works fine as i expected.
but there is no need of this so i removed it.

Related

InnerHTML in multiple fiields and more than one error statements

I am having trouble trying to get the form to validate using the onblur handler.
What I am trying to do is to get the first and last name field to display an error message if the field is blank, if it’s less than 5 , more than 18 characters, or it the user enters a number.
I would like to be able to do this using only one function so I do not need to do this for seperate functions.
Eg:
function ValidateName(field) {
var field = field.value;
var output = document.getElementById("fnameError");
if (field == "")
{
output = "field can’t be blank.";
return false;
}
else
{
output = "";
}
}
<form>
<input type="Text" id="Fname" onblur="ValidateName(this)">
<span id="fnameError"></span>
</form>
Your answer according to the question.
function ValidateName(field) {
var output = document.getElementById("fnameError");
if (field.value == "")
{
output.innerHTML = "field can’t be blank.";
}
else
{
output.innerHTML = "";
}
}
<form>
<input type="Text" id="Fname" onblur="ValidateName(this)">
<span id="fnameError"></span>
</form>
Your answer according to the the comment made on my answer.
function ValidateName() {
var outputF = document.getElementById("fnameError");
var outputL = document.getElementById("lnameError");
var outputB = document.getElementById("BothError");
var field1 = document.getElementById("Fname");
var field2 = document.getElementById("Lname");
if (field1.value == "" && field2.value == "")
{
outputF.innerHTML = "";
outputB.innerHTML = "No field can be left blank.";
outputL.innerHTML = "";
}
else if (field1.value !== "" && field2.value == "")
{
outputF.innerHTML = "";
outputB.innerHTML = "";
outputL.innerHTML = "field can’t be blank.";
}
else if (field1.value == "" && field2.value !== "")
{
outputF.innerHTML = "field can’t be blank.";
outputB.innerHTML = "";
outputL.innerHTML = "";
}
else {
outputF.innerHTML = "";
outputB.innerHTML = "";
outputL.innerHTML = "";
}
}
<form>
<input type="Text" id="Fname" onblur="ValidateName()">
<span id="fnameError"></span>
<br><br>
<input type="Text" id="Lname" onblur="ValidateName()">
<span id="lnameError"></span>
<br><br>
<span id="BothError"></span>
</form>
you can try this also
function validateform(){
var name=document.myform.name.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}
else if(name.length < 5){
alert("name must be atleast 8 characters long");
return false;
}
else if(name.length <18){
alert("text must be more than 18 characters");
return false;
}
}
<form name="myform" method="post" action="" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
<input type="submit" value="register">
</form>

i want to display multiple error in javascript

In my project I have to validate all fields when the form is submitted and display error message on same page in order list above the form field. below is my code but when click enter the data, only one error display at a time. I try multiple solution but not properly work so how do I display multiple error at same time.
function validate() {
var minnumberofchars = 6;
var maxnumberofchars = 16;
var regularexperssion = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{6,16}$/;
var letters = /^[A-Za-z]+$/;
var emailRegex = /^[A-Za-z0-9._]*\#[A-Za-z]*\.[A-Za-z]{2,5}$/;
var frname = document.getElementById('fname').value;
var lrname = document.getElementById('lname').value;
var fage = document.getElementById('age').value;
var femail = document.getElementById('email').value;
var fpassword = document.getElementById('password').value;
if (frname == "") {
document.getElementById('error').innerHTML = "enter the first name";
return false;
}
if (!letters.test(frname)) {
document.getElementById('error').innerHTML = "enter only text";
return false;
}
if (lrname == "") {
document.getElementById('error').innerHTML = "enter the last name";
return false;
}
if (!letters.test(lrname)) {
document.getElementById('error').innerHTML = "enter only text";
return false;
}
if (fage == "") {
document.getElementById('error').innerHTML = "enter the age";
return false;
}
if (isNaN(fage)) {
document.getElementById('error').innerHTML = "enter the only number";
return false;
}
if (femail == "") {
document.getElementById('error').innerHTML = "enter the email";
return false;
}
if (!emailRegex.test(femail)) {
document.getElementById('error').innerHTML = "enter the valid email";
return false;
}
if (fpassword == "") {
document.getElementById('error').innerHTML = "enter the password";
return false;
}
if (fpassword.length < minnumberofchars || fpassword.length > maxnumberofchars) {
document.getElementById('error').innerHTML = "password should between 6 to 16 character";
return false;
}
if (!regularexperssion.test(fpassword)) {
document.getElementById('error').innerHTML = "password should contain atleast one number and one special character";
return false;
}
return true;
}
Home
<form method="post" name="form1" action="add.php">
<table border="0">
<tr>
<td>First Name</td>
<td><input type="text" id="fname" name="fname"></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" id="lname" name="lname"></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" id="age" name="age"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" id="email" name="email"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" id="password" name="password"></td>
</tr>
<tr>
<td><input type="submit" value="ADD" name="submit" onclick="return validate()"></td>
</tr>
</table>
</form>
<div id='error' style='color:red'></div>
In the Validate function, take one variable and instead of returning false just append the error messages to html div or maintain the flag to check the existence of the error and at the end of the function return false if any error exist in the function and show the validations in the div.
function validate() {
var minnumberofchars = 6;
var maxnumberofchars = 16;
var regularexperssion = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{6,16}$/;
var letters = /^[A-Za-z]+$/;
var emailRegex = /^[A-Za-z0-9._]*\#[A-Za-z]*\.[A-Za-z]{2,5}$/;
var frname = document.getElementById('fname').value;
var lrname = document.getElementById('lname').value;
var fage = document.getElementById('age').value;
var femail = document.getElementById('email').value;
var fpassword = document.getElementById('password').value;
var errorMessages = '';
if (frname == "") {
errorMessages += "<br/> enter the first name";
}
if (!letters.test(frname)) {
errorMessages += "<br/> enter only text";
}
if (lrname == "") {
errorMessages += "<br/> enter the last name";
}
if (!letters.test(lrname)) {
errorMessages += "<br/> enter only text";
}
if (fage == "") {
errorMessages += "<br/> enter the age";
}
if (isNaN(fage)) {
errorMessages += "<br/> enter the only number";
}
if (femail == "") {
errorMessages += "<br/>enter the email";
}
if (!emailRegex.test(femail)) {
errorMessages += "<br/>enter the valid email";
}
if (fpassword == "") {
errorMessages += "<br/>enter the password";
}
if (fpassword.length < minnumberofchars || fpassword.length > maxnumberofchars) {
errorMessages += "<br/>password should between 6 to 16 character";
}
if (!regularexperssion.test(fpassword)) {
errorMessages += "<br/>password should contain atleast one number and one special character";
}
if (errorMessages != '') {
// Here You can also use flag to check error existence
document.getElementById('error').innerHTML = errorMessages;
return false;
}
return true;
}
There are two issues here
You are returning false after a validation, so the execution won't move forward.
Replace return false with isValid = false; (initialize this variable in the beginning of the method to true). Return this variable by the end of the method.
You need to use increment-assignment += operator instead of assignment = operator.
For example,
document.getElementById('error').innerHTML += "enter the first name" + "<br>";
Or even better use a variable instead of document.getElementById('error').innerHTML you can assign the value of that variable to the innerHTML of error

Clearing validation errors JavaScript

I have been attempting to clear messages once the user has successfully input completed the required validation rules, however I can't seem to clear all the validation errors, I did look around and tried what was suggested however it doesn't seem to have worked. I thought by placing empty innerHTML strings might work as I said it had been suggested within other posts
<form action ="" method="POST">
<span id="tryErr"></span><br>
<input type="text" id="username" placeholder="Username"><br>
<span id="usernameErr"></span><br>
<input type="text" id="email" placeholder="Email address"><br>
<span id="emailErr"></span><br>
<input type="password" id="password" placeholder="Password"><br>
<span id="passwordErr"></span><br>
<input type="submit" value="Submit" onclick=" return confirmValidation();">
</form>
JS
<script type="text/javascript">
function validateUsername(username, error){
var username = document.getElementById("username").value,
error = document.getElementById("usernameErr");
if(username == null || username==""){
return error.innerHTML = "Username is required";
return false;
}
else if(!username.match(/^[0-9a-z]+$/) || username.length < 3){
return error.innerHTML = "Username must be alphanumeric and three characters long";
return false;
}
else{
return error.innerHTML = "";
return true;
}
}
function validatePassword(password, error){
var password = document.getElementById("password").value,
error = document.getElementById("passwordErr");
if(password == null || password==""){
return error.innerHTML = "Password is required";
return false;
}
else if(password.length < 7){
return error.innerHTML = "Password must be seven characters long";
return false;
}
else{
return error.innerHTML = "";
return true;
}
}
function validateEmail(email, error){
var email = document.getElementById("email").value,
apos = email.indexOf("#"),
dotpos = email.lastIndexOf("."),
error = document.getElementById("emailErr");
if(email == null || email==""){
return error.innerHTML = "Email is required";
return false;
}
if (apos < 1 || dotpos-apos < 2 || dotpos == (email.length - 1)){
return error.innerHTML = "Please enter a valid email";
return false;
}
else{
return error.innerHTML = "";
return true;
}
}
function confirmValidation(e){
event.preventDefault(e);
if(!validateUsername()){
return false;
}
if(!validatePassword()){
return false;
}
if(!validateEmail()){
return false;
}
else{
//do something clever here
}
}
</script>
You should use onchange event on input types .
Like
<input type="text" id="username" placeholder="Username " onchange="validateUsername()">

Can't hide innerHTML after error corrected

Didn't see an answer so here goes. Error messages are using innerHTML. How do I get them to disappear once the error is corrected? Right now it just stays on. I tried resetting at the top of the script.
JSfiddle
HTML:
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="" method="post">
<h2>Contact Me</h2>
<div id="main-error"></div>
<div>
<label>Name</label>
<input placeholder="First Name" type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error"></div>
</div>
<div>
<label>Email</label>
<input placeholder="Email" type="email" name="email" id="email" tabindex="3" autofocus />
<div id="email-error"></div>
</div>
<div>
<label>Phone</label>
<input placeholder="Phone" type="text" name="phone" id="phone" tabindex="4" autofocus />
<div id="test"></div>
</div>
<div>
<button type="submit" name="submit" id="submit" tabindex="5">Send</button>
</div>
</form>
JS:
document.getElementById('name-error').innerHTML='';
document.getElementById('email-error').innerHTML='';
document.getElementById('phone-error').innerHTML='';
function validateFormOnSubmit(contact) {
var reason = "";
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validateEmpty(contact.name);
if (reason != "") {
document.getElementById("main-error").innerHTML="Test main error message area";
return false;
}
return false;
}
// validate required fields
function validateEmpty(name) {
var error = "";
if (name.value.length == 0) {
name.style.background = 'Yellow';
document.getElementById('name-error').innerHTML="The required field has not been filled in";
} else {
name.style.background = 'White';
}
return error;
}
// validate email as required field and format
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error="";
var temail = trim(email.value); // value of field with whitespace trimmed off
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (email.value == "") {
email.style.background = 'Yellow';
document.getElementById('email-error').innerHTML="Please enter an email address.";
} else if (!emailFilter.test(temail)) { //test email for illegal characters
email.style.background = 'Yellow';
document.getElementById('email-error').innerHTML="Please enter a valid email address.";
} else if (email.value.match(illegalChars)) {
email.style.background = 'Yellow';
document.getElementById('email-error').innerHTML="Email contains invalid characters.";
} else {
email.style.background = 'White';
}
return error;
}
// validate phone for required and format
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('test').innerHTML="Please enter a phone number";
phone.style.background = 'Yellow';
} else if (isNaN(parseInt(stripped))) {
document.getElementById('test').innerHTML="The phone number contains illegal characters.";
phone.style.background = 'Yellow';
} else if (!(stripped.length == 10)) {
document.getElementById('test').innerHTML="The phone number is too short.";
phone.style.background = 'Yellow';
}
return error;
}
thanks!
function validateFormOnSubmit(contact) {
reason = "";
reason += validateEmpty(contact.name);
reason+= validateEmail(contact.email);
reason+= validatePhone(contact.phone);
console.log(reason);
if ( reason.length>0 ) {
return false;
}
else {
return true;
}
}
// validate required fields
function validateEmpty(name) {
var error = "";
if (name.value.length == 0) {
name.style.background = 'Yellow';
document.getElementById('name-error').innerHTML="The required field has not been filled in";
var error = "1";
} else {
name.style.background = 'White';
document.getElementById('name-error').innerHTML='';
}
return error;
}
// validate email as required field and format
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error="";
var temail = trim(email.value); // value of field with whitespace trimmed off
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (email.value == "") {
email.style.background = 'Yellow';
document.getElementById('email-error').innerHTML="Please enter an email address.";
var error="2";
} else if (!emailFilter.test(temail)) { //test email for illegal characters
email.style.background = 'Yellow';
document.getElementById('email-error').innerHTML="Please enter a valid email address.";
var error="3";
} else if (email.value.match(illegalChars)) {
email.style.background = 'Yellow';
var error="4";
document.getElementById('email-error').innerHTML="Email contains invalid characters.";
} else {
email.style.background = 'White';
document.getElementById('email-error').innerHTML='';
}
return error;
}
// validate phone for required and format
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('test').innerHTML="Please enter a phone number";
phone.style.background = 'Yellow';
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error="5";
document.getElementById('test').innerHTML="The phone number contains illegal characters.";
phone.style.background = 'Yellow';
} else if (stripped.length < 10) {
var error="6";
document.getElementById('test').innerHTML="The phone number is too short.";
phone.style.background = 'Yellow';
}
else {
phone.style.background = 'White';
document.getElementById('test').innerHTML='';
}
return error;
}
http://jsfiddle.net/tX5y5/59/
I have just changed place of inner html cleaning... and i have added some changes in whole validation (it didn't worked before properly).
You'll need to register a listener for when the user changes one of your input fields and run your validation function in the listener. Something like this:
document.getElementById('name').addEventListener("change", validateFormOnSubmit);
document.getElementById('email').addEventListener("change", validateFormOnSubmit);
document.getElementById('phone').addEventListener("change", validateFormOnSubmit);
If at all possible I'd recommend using an existing library for form validation (but you probably already knew that).

JavaScript Alert/Confirm Error

Currently when new users register at my website, they have to fill out some forms. If their password is too short, doesn't match, they don't fill out all of the fields, or any other error, I want to alert them of it. Currently it does not alert them, so I switched to confirm. That didn't work either so I considered using showModalDiaglog. That also didn't work, I am out of Ideas. I currently have this:
HTML
<form>
First Name:<br/> <input id="firstname"/><br/>
Last Name: <br/> <input id="lastname"/><br/>
Age: <br/> <input id="age"/><br/>
Your Email:<br/> <input id="email"/><br/>
Username: <br/> <input id="username"/><br/>
Password: <br/> <input id="password"/><br/>
Confirm Password:<br/> <input type="password" id="passwordconfirm"/><br/>
<br/>
<button size=20 onClick='getRegistrationFields()'>Submit</button>
</form>​
JavaScript
function getRegistrationFields() {
var first = document.getElementById("firstname").value;
var last = document.getElementById("lastname").value;
var email = document.getElementById("email").value;
var age = document.getElementById("age").value;
var username = document.getElementById("username").value;
var password = document.getElemetnById("password").value;
var confirm = document.getElementById("passwordconfirm").value;
var empty = "";
if ((first === empty) || (last === empty) || (email === empty) || (age === empty)
|| (username === empty) || (password === empty) || (confirm === empty)) {
var message = "Not all of the fields are filled out";
prompt(message);
//showModalWindow("fields");
return false;
}
else {
age = parseInt(age);
if (password.length < 10) {
var message2 = "Password must be at least 10 characters long";
prompt(message2);
//showModalWindow("passwordlength");
return false;
}
else if (password != confirm) {
var message3 = "Passwords Do not match";
prompt(message3);
//showModalWindow("passwordmatch");
return false;
}
else if (age < 18) {
var message4 = "You must be older to register for this software.";
prompt(message4);
//showModalWindow("young");
return false;
}
else {
var message5 = "All of the fields are correct. We will be processing your request";
prompt(message5);
//showModalWindow("success");
return true;
}
}
}
function showModalWindow(fileName) {
window.showModalDialog("alerts/" + url + ".html", "", "resizable: no; height: 150; width: 350;");
}
try
html:
<button size="20" id="btn_submit">Submit</button>
js:
var btn_submit = document.getElementById("btn_submit");
btn_submit.onclick = getRegistrationFields;
Make it easy on yourself.
<input type="password" class="password" />
<input type="text" class="age" />
<script type="text/javascript">
!(function () {
var txBxs = document.querySelectorAll('input[type=textbox]'),
i = txBxs.length;
while (i--) {
tkBxs[i].onchange = textBoxCheck;
};
}());
//
function textBoxCheck() {
//
switch (this.class) {
//
case 'password':
if (this.value.length < 10)
{ alert('Password to short'); };
break;
//
case 'age':
if (+this.value < 18)
{ alert('To young kiddo!'); };
break;
};
};
</script>
There is a typo:
var password = document.getElemetnById("password").value;
You wrote getElemetnById instead of getElementById.

Categories

Resources