I'm creating a "Sign Up" form for my new website, but got a problem with a jQuery/JS function that is supposed to check for some conditions to be reached.
$(function checkform() {
if (this.is("#username")) {
var validchars = /^[a-zA-Z0-9\s]+$/;
var nameHasError;
if (this.val().length < 6 && this.val().length > 26) {
nameHasError = true;
this.parent("div").addClass("has-error");
} else if (!(validchars.test(this).val())) {
nameHasError = true;
this.parent("div").addClass("has-error");
} else {
nameHasError = false;
this.parent("div").removeClass("has-error");
};
} else if (this.is("#password")) {
var passHasError;
if (this.val().length < 5 && this.val().length > 45) {
passHasError = true;
this.parent("div").addClass("has-error");
} else {
passHasError = false;
this.parent("div").removeClass("has-error");
};
};
});
Here's the JSFiddle with HTML part (I'm using bootstrap on my website but preferred to set a specific class on the fiddle)
Best regards
You are mixing vanilla javascript with jquery syntax. this.is('#username') is not javascript.
Use this.id == "username" (vanilla js) instead
OR
$(this).is('#username') (jquery)
Take care with the scope in your functions
There are multiple issues in the code
You have defined the checkForm in $(), so the function will be available only inside the dom ready handler, so your onkeypress will throw an error
When dom ready handler invokes the function this will be the document object which does not have the is function
The character size validation should use || not &&
So, ti will be better to use a jQuery event handler with both the fields having their own validation function like
jQuery(function($) {
$('#username').on('keypress', function() {
var validchars = /^[a-zA-Z0-9\s]+$/;
var nameHasError = false;
var $this = $(this),
value = this.value;
if (value.length < 6 || value.length > 26) {
nameHasError = true;
} else if (!validchars.test(value)) {
nameHasError = true;
};
$this.parent("div").toggleClass("has-error", nameHasError);
});
$('#password').on('keypress', function() {
var passHasError = false;
var $this = $(this),
value = this.value;
if (value.length < 5 || value.length > 45) {
passHasError = true;
};
$this.parent("div").toggleClass("has-error", passHasError);
});
});
.has-error {
background-color: red;
}
.has-success {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" placeholder="Between 6 and 26 characters">
<span id="unameError"></span>
</div>
<br/>
<div class="">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
<span id="passError"></span>
</div>
</div>
function checkform() {
if ($(this).is("#username")) {
var validchars = /^[a-zA-Z0-9\s]+$/;
var nameHasError;
if ($(this).val().length < 6 || $(this).val().length > 26) {
nameHasError = true;
$(this).parent("div").addClass("has-error");
} else if (!(validchars.test($(this).val()))) {
nameHasError = true;
$(this).parent("div").addClass("has-error");
} else {
nameHasError = false;
$(this).parent("div").removeClass("has-error");
};
} else if ($(this).is("#password")) {
var passHasError;
if ($(this).val().length < 5 || $(this).val().length > 45) {
passHasError = true;
$(this).parent("div").addClass("has-error");
} else {
passHasError = false;
$(this).parent("div").removeClass("has-error");
};
};
}
$(function () {
$('input').on('keyup', checkform);
})
.has-error {
background-color: red;
}
.has-success {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" placeholder="Between 6 and 26 characters">
<span id="unameError"></span>
</div>
<br/>
<div class="">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
<span id="passError"></span>
</div>
</div>
Related
I am developing in my final year school project. Now I faced a problem. Some of the onsubmit function in my forms are not functioning well.
The problem is:
I am validating the details filled in in the form. But although the innerHTML already pointed out the wrong by using getElementById, the form still can be submitted. How to stop the form from submitting?
The function does not return any true or false value.
I've already checked through the code. But I can't find the mistakes.
I tried to change the function validate() to window.validate = function(), it does not work well either.
I tried to change the validate function to only return false. The form is still submitting.
I tried event preventDefault but the outcomes become I cannot submit the form.
Javascript part
function check_location() {
var user_address = document.getElementById("location");
var user_address_mess = document.getElementById("addressvalidate");
var checkaddress;
if (user_address.value == "") {
//.....
return false;
} else if (user_address.value.length <= 10) {
//.....
return false;
} else {
//....
return true;
}
}
function check_stime() {
var starttime = document.getElementById("starttime");
var mess_starttime = document.getElementById("mess_starttime");
var check1;
if (starttime != null) {
if (starttime.value == "") {
//...
return false;
}
else if (starttime.value < "08:00" && starttime > "19:00") {
//...
return false;
}
else {
//...
return true;
}
}
}
function check_date() {
today = new Date();
today.setDate(today.getDate() + 14);
var eventdate = document.getElementById("date").value;
eventdate1 = new Date(eventdate);
var mess_date = document.getElementById("mess_date");
var check2;
if (document.getElementById("checkdate") != null) {
var checkdate = document.getElementById("checkdate").innerHTML;
}
if (eventdate != null) {
if (eventdate.value == "") {
//...
return false;
}
else if (eventdate1 <= today) {
//...
return false;
}
else {
//...
return true;
}
}
}
function check_etime() {
var starttime = document.getElementById("starttime");
var endtime = document.getElementById("endtime");
var mess_endtime = document.getElementById("mess_endtime");
var eventdate = document.getElementById("eventdate");
var check3;
if (endtime != null) {
if (endtime.value == "") {
// ...
return false;
}
else if (endtime.value == starttime.value || endtime.value <= starttime.value) {
// ...
return false;
}
else if (endtime.value <= starttime.value && eventdate.value <= fulldate) {
// ...
return false;
}
else if (endtime.value < "09:00" && endtime.value > "22.00pm") {
// ...
return false;
}
else {
//...
return true;
}
}
}
function validate() {
checkstime = check_stime();
checketime = check_etime();
checkdate = check_date();
checklocation = check_location();
if (checklocation == false || checkstime == false || checketime == false || checkdate == false) {
return false;
} else {
return true;
}
}
HTML Part
<div class="g-text-center--xs g-margin-b-40--xs">
<h2 class="g-font-size-30--xs g-color--black">Booking Form</h2>
</div>
<br>
<form autocomplete="off" name="form_submit" onsubmit=" return validate();" method="post" action="">
<div class="g-margin-b-30--xs">
<p><b>Package Name :</b>
<input type="text" name="pname" class="form-control s-form-v3__input g-bg-color--white-opacity-lightest" value="<?php echo $pack1['package_name']?>" style="width:200px; font-weight:bold; color:black;" disabled>
</p>
</div>
<div class="g-margin-b-30--xs">
<p><b>Package Price :</b>
<input type="text" name="pprice" class="form-control s-form-v3__input g-bg-color--white-opacity-lightest" value="RM <?php echo $pack1['package_price']?>" style="width:200px; font-weight:bold; color:black;" disabled>
</p>
</div>
<div class="g-margin-b-30--xs">
<b>Event Date :</b>
<input onfocusout="check_date()" name="date" id="date" type="date" class="form-control s-form-v3__input g-bg-color--white-opacity-lightest" style="width:400px; color:black;">
<span id="mess_date" style="color:red;font-weight:normal;"></span>
</div>
<div class="g-margin-b-30--xs">
<b>Start Time :</b>
<input onfocusout="check_stime()" name="starttime" id="starttime" type="time" class="form-control s-form-v3__input g-bg-color--white-opacity-lightest" style="width:500px;" />
<span id="mess_starttime" style="color:red;font-weight:normal;"></span>
</div>
<div class="g-margin-b-30--xs">
<b>End Time :</b>
<input onfocusout="check_etime()" name="endtime" id="endtime" type="time" class="form-control s-form-v3__input g-bg-color--white-opacity-lightest" style="width:500px;" />
<span id="mess_endtime" style="color:red;font-weight:normal;"></span>
</div>
<b>Event Location : </b>
<br>
<textarea class="form-control s-form-v2__input" name="location" id="location" style=" width:500px; font-weight:bold; text-align:left;" onfocusout="check_location()"></textarea>
<span style="color:red;font-weight:normal;" id="addressvalidate"></span>
<div class="g-text-center--xs">
<br>
<button style="margin-bottom:50px;" type="submit" id="submit" name="addtocart" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Submit</button>
<div class="clearfix"> </div>
</div>
</form>
I want to prevent the form from submitting when there is something wrong.
You can easily fix this by changing your code to this.
<form id="myForm" onsubmit="event.preventDefault(); validate();">
and change validate() javascript function to this.
function validate() {
checkstime = check_stime();
checketime = check_etime();
checkdate = check_date();
checklocation = check_location();
if (checklocation == false || checkstime == false || checketime == false || checkdate == false) {
return false;
} else {
document.getElementById("myForm").submit();
}
}
On click of the submit button add something like below
<button onclick="return validate()" style="margin-bottom:50px;" type="submit" id="submit" name = "addtocart" class = "btn btn-primary"><span class = "glyphicon glyphicon-floppy-disk"></span> Submit</button>
In the validate() function ,you if you return true it will submit,if you return false, it will not submit form,there you can show the error message
Remove everything from the form tag all the submit lines and simply give it a unique id and same goes to the button tag too something like this
<form id ="my_form" action="/action_page.php">
<button id="u_id">submit</button>
</form>
Then in java script part
var form = document.getElementById("my_form");
document.getElementById("u_id").addEventListener("click", function () {
checkstime = check_stime();
checketime = check_etime();
checkdate = check_date();
checklocation = check_location();
if (checklocation == false || checkstime == false || checketime == false || checkdate == false) {
//show error msg
} else {
form .submit();
}
});
Basically, I want to change value on, say textbox2, when the value of textbox1 is changed by a button function. I know that it is possible to include the function on the button to change the value on the textbox2, but I don't want that. Is it possible?
Here's what I tried so far on JSFiddle https://jsfiddle.net/xpvt214o/387300/
HTML code:
<button id="button1">button</button>
<input type="text" id="outputtext1" value="1" readonly/>
<input type="text" id="outputtext2" value="" />
JavaScript:
jQuery('#button1').on('click', function() {
document.getElementById("outputtext1").value = parseInt(document.getElementById("outputtext1").value) +1;
});
jQuery('#outputtext1').on('change', function() {
//I know that this logic can be put in onClick function above instead
var number = document.getElementById("outputtext1").value;
if( number <= 3){
document.getElementById("outputtext2").value = "low";
} else if (number < 10){
document.getElementById("outputtext2").value = "medium";
} else if (number >= 10){
document.getElementById("outputtext2").value = "high";
}
});
Thank you in advance!
You can use jQuery('#outputtext1').trigger("change"); in the button element click event.
Example:
jQuery('#button1').on('click', function() {
document.getElementById("outputtext1").value = parseInt(document.getElementById("outputtext1").value) + 1;
jQuery('#outputtext1').trigger("change");
});
jQuery('#outputtext1').on('change', function() {
var number = document.getElementById("outputtext1").value;
if (number <= 3) {
document.getElementById("outputtext2").value = "low";
} else if (number < 10) {
document.getElementById("outputtext2").value = "medium";
} else if (number >= 10) {
document.getElementById("outputtext2").value = "high";
}
});
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1">button</button>
<input type="text" id="outputtext1" value="1" readonly/>
<input type="text" id="outputtext2" value="" />
Try this:Change the value for outputtext1 and fire change event on it
jQuery('#button1').on('click', function() {
var value = jQuery("#outputtext1").val();
value = (parseInt(value) || 0) + 1;
jQuery("#outputtext1").val(value).change();
});
jQuery('#outputtext1').on('change', function() {
var number = (parseInt($(this).val()) || 0) + 1;
if( number <= 3){
jQuery("#outputtext2").val("low");
} else if (number < 10){
jQuery("#outputtext2").val("medium");
} else if (number >= 10){
jQuery("#outputtext2").val("high");
}
});
JSFiddle
NOTE: You can use jQuery id selector and '.va()` function instead of Javacript as shown in code above.
You could use $('#outputtext1').trigger("change") on button click
DEMO
$('#button1').on('click', function() {
$('#outputtext1').val(+$('#outputtext1').val()+1);
$('#outputtext1').trigger("change");
});
$('#outputtext1').on('change', function() {
var number = document.getElementById("outputtext1").value;
if (number <= 3) {
document.getElementById("outputtext2").value = "low";
} else if (number < 10) {
document.getElementById("outputtext2").value = "medium";
} else if (number >= 10) {
document.getElementById("outputtext2").value = "high";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1">button</button>
<input type="text" id="outputtext1" value="1" readonly/>
<input type="text" id="outputtext2" value="" />
Either you can trigger the change event or create a generic function and call it on both click and change event. Its better to call generic function rather then triggering the event from event.
// find elements
var banner = $("#banner-message")
var button = $("button")
$('#button1').on('click', function() {
document.getElementById("outputtext1").value = parseInt(document.getElementById("outputtext1").value) + 1;
$('#outputtext1').trigger('change');
});
$('#outputtext1').on('change', function() {
var number = document.getElementById("outputtext1").value;
if (number <= 3) {
document.getElementById("outputtext2").value = "low";
} else if (number < 10) {
document.getElementById("outputtext2").value = "medium";
} else if (number >= 10) {
document.getElementById("outputtext2").value = "high";
}
});
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1">button</button>
<input type="text" id="outputtext1" value="1" />
<input type="text" id="outputtext2" value="" />
<!-- this should be changed when the value of outputtext1 is changing -->
// find elements
var banner = $("#banner-message")
var button = $("button")
$('#button1').on('click', function() {
document.getElementById("outputtext1").value = parseInt(document.getElementById("outputtext1").value) + 1;
validateInput();
});
$('#outputtext1').on('change', function() {
validateInput();
});
function validateInput() {
var number = document.getElementById("outputtext1").value;
if (number <= 3) {
document.getElementById("outputtext2").value = "low";
} else if (number < 10) {
document.getElementById("outputtext2").value = "medium";
} else if (number >= 10) {
document.getElementById("outputtext2").value = "high";
}
}
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1">button</button>
<input type="text" id="outputtext1" value="1" />
<input type="text" id="outputtext2" value="" />
<!-- this should be changed when the value of outputtext1 is changing -->
try this fiddle
I am getting the selector attribute value with $('#outputtext1').attr('value') so that it will not break and change the value at runtime[Please check the value in DOM]. At the same time I am triggering a change event on button click.
jQuery('#button1').on('click', function() {
var x = $('#outputtext1').attr('value');
x = parseInt(x) +1;
$('#outputtext1').attr("value", x);
jQuery('#outputtext1').trigger("change");
});
jQuery('#outputtext1').on('change', function() {
var number = $('#outputtext1').attr('value');
if( number <= 3){
document.getElementById("outputtext2").value = "low";
} else if (number < 10){
document.getElementById("outputtext2").value = "medium";
} else if (number >= 10){
document.getElementById("outputtext2").value = "high";
}
});
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1">button</button>
<input type="text" id="outputtext1" value="1" />
<input type="text" id="outputtext2" value="" />
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'm search but i'm not 100% how you get this to resubmit, using new information, I've got all the errors up and showing as appropriate, but in terms of, how to hit the submit button again, and then it reassesses the form; how do i go about this? Any help would be appreciated.
html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>RATool</title>
<link rel="stylesheet" type="text/css" href="cfcss.css">
<script src="cf.js"></script>
</head>
<body>
<h1> Health Authority </h1>
<h2> Contact Form </h2>
<form>
<fieldset>
<label for="fname">First Name:</label>
<input name="fname" id="fname" class="formfield" type="text">
<span id="errfname" class="error">*This is required</span>
<span id="errfname1" class="error">*Name fields must have more than one character, and do not contain numbers
or other non-allowed alphabetic characters. The only character the last name
field should legitimately contain is a hyphen (e.g. Whittaker-Jones).</span>
<span id="errfname2" class="error">*This can only contain alphabetic numbers and if desired, one hyphen</span>
<br>
<label for="sname">Surname:</label>
<input name="sname" id="sname" class="formfield" type="text">
<span id="errsname" class="error">*This is required</span>
<span id="errsname1" class="error">*Name fields must have more than one character, and do not contain numbers
or other non-allowed alphabetic characters. The only character the last name
field should legitimately contain is a hyphen (e.g. Whittaker-Jones).</span>
<span id="errsname2" class="error">*This can only contain alphabetic numbers and if desired, one hyphen</span>
<br>
<label for="title">Title: </label>
<select name="title" id="title">
<option value="Please select">Please select</option>
<option value="Mr.">Mr.</option>
<option value="Ms.">Ms.</option>
<option value="Mrs.">Mrs.</option>
<option value="Miss.">Miss.</option>
<option value="Master.">Master.</option>
</select>
<span id="errtitle" class="error">*This is required</span>
<br>
<br>
<br>
<label for="HANo">Health Authority Number:</label>
<input name="HANo" id="HANo" class="formfield"type="text">
<span id="errHANo" class="error">*This is required</span>
<span id="errHANo2" class="error">*This must be in format ZHA123456 (ZHA followed by 6 numbers)</span>
<br>
<br>
<label for="email">Email:</label>
<input name="email" id="email" class="formfield"type="text">
<span id="erremail" class="error">*This is required</span>
<span id="erremail2" class="error">*Please enter a valid email</span>
<br>
<br>
<br>
<label for="telno">Telephone Number:</label>
<input name="telno" id="telno" class="formfield" type="text">
<span id="errtelno" class="error">* If a telephone number is entered, then it should contain only numbers, not
letters, or other disallowed characters. A valid Zedland telephone number has
11 digits (no spaces)</span>
<span id="errtelno1" class="error">*This must just be numbers</span>
<br>
<button onclick="checkForm()">Submit</button>
</fieldset>
</form>
</body>
</html>
javascript
function checkForm(){
var errors=document.getElementsByClassName('error');
for(var i=0;i<errors.length;i++){
errors[i].style.display='none';
}
if (document.getElementById("fname").value == "" ) {
document.getElementById("errfname").style.display = "inline";
document.getElementById("errfname").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("fname").value.length < 2 ) {
document.getElementById("errfname1").style.display = "inline";
document.getElementById("errfname1").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("fname").value.length > 1) {
checkFName();
e.preventDefault();
}
if (document.getElementById("sname").value == "" ) {
document.getElementById("errsname").style.display = "inline";
document.getElementById("errsname").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("sname").value.length < 2 ) {
document.getElementById("errsname1").style.display = "inline";
document.getElementById("errsname1").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("sname").value.length > 1) {
checkSName();
e.preventDefault();
}
if (document.getElementById("title").value == "Please select" ) {
document.getElementById("errtitle").style.display = "inline";
document.getElementById("errtitle").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("HANo").value == "" ) {
document.getElementById("errHANo").style.display = "inline";
document.getElementById("errHANo").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("HANo").value.length > 0) {
if (checkHANo());
e.preventDefault();
}
if (document.getElementById("email").value == "" ) {
document.getElementById("erremail").style.display = "inline";
document.getElementById("erremail").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("email").value.length > 0 ) {
if(checkEmail());
e.preventDefault();
}
if (document.getElementById("telno").value.length != 11 ) {
document.getElementById("errtelno").style.display = "inline";
document.getElementById("errtelno").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("telno").value == /^\d+$/ ) {
document.getElementById("errtelno1").style.display = "inline";
document.getElementById("errtelno1").style.visibility = "visible";
e.preventDefault();
}
}
function checkEmail(){
var email = document.getElementById('email');
var emailRegEx = /[-\w.]+#([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
if (!emailRegEx.test(email.value)) {
document.getElementById("erremail2").style.display="inline";
document.getElementById("erremail2").style.visibility = "visible";
return true;
}
e.preventDefault();
}
function checkHANo(){
var HANo = document.getElementById("HANo");
var hanoRegEx = /[ZHA]\d{6}/;
if (!hanoRegEx.test(HANo.value)) {
document.getElementById("errHANo2").style.display = "inline";
document.getElementById("errHANo2").style.visibility = "visible";
return true;
}
e.preventDefault();
}
function checkFName(){
var first = document.getElementById("fname");
var firstRegEx = /^[a-zA-Z-]{2,40}$/;
if (!firstRegEx.test(first.value)){
document.getElementById("errfname2").style.display = "inline";
document.getElementById("errfname2").style.visibility = "visible";
return true;
}
e.preventDefault();
}
function checkSName(){
var sec = document.getElementById("sname");
var secRegEx = /^[a-zA-Z-]{2,40}$/;
if (!secRegEx.test(sec.value)){
document.getElementById("errsname2").style.display = "inline";
document.getElementById("errsname2").style.visibility = "visible";
return true;
}
e.preventDefault();
}
Your error messages are displaying by default. To hide those add the CSS class below:
.error{ display:none; }
Add this piece of code at the beginning of checkForm() to re-hide the message when error is corrected. Eg:
var errors=document.getElementsByClassName('error');
for(var i=0;i<errors.length;i++){
errors[i].style.display='none';
}
Instead of calling the formCheck() function on onclick of the button, call it onsubmit of the form with a return. Like
<form method="post" action="yourpage" onsubmit="return checkForm()">
To show all errors, declare a variable with default value as true like var isValid=true; just above/below the for loop
Eg:
function checkForm(){
var isValid = true;
var errors=document.getElementsByClassName('error');
for(var i=0;i<errors.length;i++){
errors[i].style.display='none';
}
if (document.getElementById("fname").value == "" ) {
document.getElementById("errfname").style.display = "inline";
document.getElementById("errfname").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("fname").value.length < 2 ) {
document.getElementById("errfname1").style.display = "inline";
document.getElementById("errfname1").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("fname").value.length > 1) {
isValid = checkFName();
}
if (document.getElementById("sname").value == "" ) {
document.getElementById("errsname").style.display = "inline";
document.getElementById("errsname").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("sname").value.length < 2 ) {
document.getElementById("errsname1").style.display = "inline";
document.getElementById("errsname1").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("sname").value.length > 1) {
isValid = checkSName();
}
if (document.getElementById("title").value == "Please select" ) {
document.getElementById("errtitle").style.display = "inline";
document.getElementById("errtitle").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("HANo").value == "" ) {
document.getElementById("errHANo").style.display = "inline";
document.getElementById("errHANo").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("HANo").value.length > 0) {
isValid = checkHANo();
}
if (document.getElementById("email").value == "" ) {
document.getElementById("erremail").style.display = "inline";
document.getElementById("erremail").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("email").value.length > 0 ) {
if(checkEmail());
isValid = false;
}
if (document.getElementById("telno").value.length != 11 ) {
document.getElementById("errtelno").style.display = "inline";
document.getElementById("errtelno").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("telno").value == /^\d+$/ ) {
document.getElementById("errtelno1").style.display = "inline";
document.getElementById("errtelno1").style.visibility = "visible";
isValid = false;
}
return isValid;
}
NOTE: You have to return false from other functions such as checkEmail(),checkHANo() also if there is error. It seems you are returning only true. And remove all e.preventDefault()
That's it
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