I'm working on a project and I am trying to add checks for the inputs on the form. I want it to only submit and move to the URL if the requirements are met. I'm using Javascript to check this. Currently, my code doesn't return any errors in the console but when I press submit even with blank inputs it submits and moves to the next page.
// Form Controls
const form = document.getElementById('form');
const username = document.getElementById('username');
const room = document.getElementById('room');
// Show input error message
function showError(input, message) {
const formControl = input.parentElement;
formControl.className = 'form-control error';
const small = formControl.querySelector('small');
small.innerText = message;
}
// Show Success outline
function showSuccess(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
// Check required fields
function checkRequired(inputArr) {
inputArr.forEach(function(input) {
if (input.value.trim() === '') {
showError(input, `${getFieldName(input)} is required`);
} else {
showSuccess(input);
}
});
}
// Get fieldName
function getFieldName(input) {
return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}
// Event Listeners
form.addEventListener('submit', function(e) {
e.preventDefault();
checkRequired([username]);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="../static/style.css" rel="stylesheet">
<title>ChatR</title>
<script src="{{ url_for('static', filename='scripts.js') }}"></script>
</head>
<body>
<div class="container-head">
<div class="header">
<h1>MyApp</h1>
</div>
</div>
<div class="container">
<form action="{{url_for('chat') }}" class="form" id="form" method="POST">
<div class="form-control">
<input type="username" id="username" name="username" placeholder="Enter username">
<small>Error Message</small>
</div>
<div class="form-control">
<input type="room" id="room" name="room" placeholder="Enter room">
<small>Error Message</small>
</div>
<button type="submit" class="btn btn-big">Start Chat</button>
</form>
</div>
</body>
</html>
New Code that works:
// Check required fields
function checkRequired(inputArr) {
var success = true;
inputArr.forEach(function(input) {
if (input.value.trim() === '') {
success = false;
showError(input, `${getFieldName(input)} is required`);
} else {
showSuccess(input);
}
});
return success;
}
// Check input length
function checkLength(input, min, max) {
var success = true;
if(input.value.length < min) {
showError(input, `${getFieldName(input)} must be at least ${min} characters`);
console.log(input);
success = false;
} else if(input.value.length > max) {
showError(input, `${getFieldName(input)} must be less than ${max} characters`);
success = false;
} else {
showSuccess(input);
}
return success;
}
// Get fieldName
function getFieldName(input) {
return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}
// Event Listeners
form.addEventListener('submit', function(e) {
e.preventDefault();
if(checkRequired([username, room]) && checkLength(username, 3, 15)){
form.submit();
}
});
I made some changes to the code so it submits when it is successful.
The first thing is to have checkRequired return true or false indicating if the validation was successful or not.
Second, check that value in the submit event listener and submit the form if it is valid.
// Check required fields, returning true/false if valid.
function checkRequired(inputArr) {
var success = true; // <= assume success
inputArr.forEach(function(input) {
if (input.value.trim() === '') {
success = false; // <= if anything fails, the not successful
showError(input, `${getFieldName(input)} is required`);
} else {
showSuccess(input);
}
});
return success; // return value indicating success
}
// Event Listeners
form.addEventListener('submit', function(e) {
e.preventDefault();
// submit only if validation is successful
if(checkRequired([username, room])){
form.submit();
}
});
By the way, you might want to add room to the array of inputs being validated.
The problem here is Because the element is not found in the DOM while the script is running with this it will run after dom gets loaded.
So solution for this is to add a this line on top of scripts.js
document.addEventListener("DOMContentLoaded", () => {
//whole scripts.js in this section
//ends with this
})
with this it will loads and check if DOM is loaded or not and after that your script will work
Related
I have a form which contain elements (checkboxes) that will be produced using JavaScript and I want to check if at least one of them is checked. Also, I have a few inputs that I want to check if at least one of them has value. The initial problem was The code I wrote displayed the error message but immediately submits the form. I can't use server side validation here because these items are created through JS. and I'm not sure if I can use server side validation to check if at least one input field has value.
For this problem I tried using e.preventDefault(); , it stops the form from submitting if there is no value or checkbox not checked but if there was a value it will still not submit the form
This the code I tried
$(function () {
$("#SubmitForm-btn").click(function () {
$("#fupForm").submit(function (e) {
e.preventDefault();
var valid = true;
//here I'm checking if any of the input field has value.
$('#dataTable tbody tr td input[type=text]').each(function () {
var text_value = $(this).val();
if (!hasValue(text_value)) {
valid = false;
$("#tableEmpty").html("Please Choose a Service");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
})
//here I'm checking if any of the checkbox is checked.
$('.check').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#Person_errorMSG").html("Please choose a person");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
//here I'm checking if any of the checkbox is checked.
$('.Fromcheck').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#From_errorMSG").html("Please choose a City");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
//here I'm checking if any of the checkbox is checked.
$('.Tocheck').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#To_errorMSG").html("Please choose a To city");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
});
});
});
You should prevent the button click event, instead of the form submit action.
Please refer the following sample code:
In the View page, we have a mainform.
<form id="mainform" asp-action="AddAttribute">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="AttributeId" class="control-label"></label>
<input asp-for="AttributeId" class="form-control" />
<span asp-validation-for="AttributeId" class="text-danger"></span>
</div>
...
<div class="form-group">
Is Submit <input type="checkbox" class="isSubmit" />
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" id="SubmitForm-btn" />
</div>
</form>
At the end of the above page, add the following script:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(function () {
$("#SubmitForm-btn").click(function () {
event.preventDefault(); //prevent the default submit action.
//check if the checkbox is checked or not.
var ischecked = $(".isSubmit").last().is(":checked");
if (ischecked) {
//alert("Checked");
//if the cleckbox checked, submit the form.
$("#mainform").submit();
}
else {
//alert("Unchecked");
//show notification message. and the form will not submit.
}
});
});
</script>
}
The result as below:
How do I force a user to enter a valid time and valid number before pressing the button "Show"?
I have two fields in my html code and I found two good validation scripts in JS. One for time and one to determine if input field has a numeric value.
I can't change anything in the HTML.
function checkTime() {
re = /^\d{1,2}:\d{2}([ap]m)?$/;
if (time_untilopt.value != '' && !time_untilopt.value.match(re)) {
alert("Wrong time!");
return false;
}
}
function checkRoomNr() {
var numbers = /^[0-9]+$/;
if (roomopt.value.match(numbers)) {
console.log("is number");
} else {
console.log("not a number!");
}
}
<div>
<label for="time-until">Time</label>
<input type="text" id="time-until">
</div>
<div>
<label for="room">Room</label>
<input type="text" id="room">
</div>
<button id="show-schedule">Show</button>
If you want the validation to take place as data is being entered into the fields, you should set your functions up to run on the input event of the fields. If you want to wait until the user leaves the field and has made changes to the value of the field, then you can use the change event of the fields.
But, you'll also want the data to be checked when the form that contains the fields is submitted, so you need to set up a submit event handler for the form as well.
The way to connect a function to an event is to register the function as an "event handler" and that is done (using modern standards-based code) with the .addEventListener() method:
// First, get references to the elements you'll want to work with.
// And, use those variable names to reference the elements in your
// code, not their IDs.
var timeUntil = document.getElementById("time-until");
var room = document.getElementById("room");
var form = document.querySelector("form");
// We'll set up a variable to keep track of whether there are any errors
// and we'll assume that there are not any initially
var valid = true;
// Set up the event handling functions:
timeUntil.addEventListener("change", checkTime);
room.addEventListener("change", checkRoomNr);
form.addEventListener("submit", validate);
function checkTime(evt){
re = /^\d{1,2}:\d{2}([ap]m)?$/;
if(timeUntil.value != '' && !timeUntil.value.match(re)) {
console.log("Wrong time!");
valid = false; // Indicate an error
} else {
valid = true;
}
}
function checkRoomNr(evt){
var numbers = /^[0-9]+$/;
if(!room.value.match(numbers)){
console.log ("not a number!");
valid = false; // Indicate an error
} else {
valid = true;
}
}
// This function is called when the form is submitted
function validate(evt){
// Invoke the validation functions in case the fields have not been checked yet
checkTime();
checkRoomNr();
if(!valid){
evt.preventDefault(); // Cancel the form's submission
console.log("Submission cancelled due to invalid data");
}
}
<form action="#">
<div>
<label for="time-until">Time</label>
<input type="text" id="time-until">
</div>
<div>
<label for="room">Room</label>
<input type="text" id="room">
<div>
<button id="show-schedule">Show</button>
<form>
function checkTime( val ) { //Pass a value
return /^\d{1,2}:\d{2}([ap]m)?$/.test( val ); //Return a boolean
}
function checkNum( val ) { //Pass a value
return /^\d+$/.test( val ); //Return a boolean
}
const time = document.getElementById("time-until"),
room = document.getElementById("room"),
show = document.getElementById("show-schedule");
function validateForm () {
show.disabled = (checkTime( time.value ) && checkNum( room.value )) === false;
}
[time, room].forEach( el => el.addEventListener("input", validateForm) );
<div>
<label for="time-until">Time</label>
<input type="text" id="time-until">
</div>
<div>
<label for="room">Room</label>
<input type="text" id="room">
</div>
<!-- MAKE BUTTON DISABLED -->
<button id="show-schedule" disabled>Show</button>
Now you can reuse your functions like checkTime( val ) regardless of the input ID.
This may be a starting point basically you need to add event handlers and wire up time_untiloptand time_untilopt and add disabled to the show button. and listen for changes. There many ways, this is just an idea.
const button = document.getElementById('show-schedule');
const time_untilopt = document.getElementById('time-until');
const roomopt = document.getElementById('room');
function checkTime() {
re = /^\d{1,2}:\d{2}([ap]m)?$/;
if (time_untilopt.value != '' && !time_untilopt.value.match(re)) {
alert("Wrong time!");
return false;
}
return true;
}
function checkRoomNr() {
var numbers = /^[0-9]+$/;
if (roomopt.value.match(numbers)) {
console.log("is number");
return true;
} else {
console.log("not a number!");
return false;
}
}
function change() {
button.disabled = !(checkTime() && checkRoomNr());
}
<div>
<label for="time-until">Time</label>
<input type="text" id="time-until" onchange="change()">
</div>
<div>
<label for="room">Room</label>
<input type="text" id="room" onchange="change()">
</div>
<button id="show-schedule" disabled="true">Show</button>
Inside both of your functions you'll want to set up your variables (time_untilopt and roomopt) to actually point to your two <input> fields. Then you'll simply want to return true if they pass validation, and return false if they don't.
To trigger these checks, you'll want to set up an onlick attribute for your submission, which is tied in to a third function, which I have named show(). This third function should conditionally check that both of the other functions return true. If they do, all is good, and you can continue with the submission. If they're not good, simply return false in this function as well.
This can be seen in the following:
function checkTime() {
re = /^\d{1,2}:\d{2}([ap]m)?$/;
var time_untilopt = document.getElementById('time-until');
if (time_untilopt.value != '' && !time_untilopt.value.match(re)) {
return true;
}
else {
console.log("Wrong time!");
return false;
}
}
function checkRoomNr() {
var numbers = /^[0-9]+$/;
var roomopt = document.getElementById('room');
if (roomopt.value.match(numbers)) {
return true;
} else {
console.log("The room number is not a number!");
return false;
}
}
function show() {
if (checkTime() && checkRoomNr()) {
console.log('Both validations passed!');
return true;
}
else {
return false;
}
}
<div>
<label for="time-until">Time</label>
<input type="text" id="time-until">
</div>
<div>
<label for="room">Room</label>
<input type="text" id="room">
</div>
<button id="show-schedule" onclick="show()">Show</button>
Also note that your checkTime() function is actually doing the exact opposite of what you want; if the time is not empty and matches the validation, you want to return true, not false. This has been corrected in the above example.
Hope this helps! :)
I'm trying to change the value of my input text field before submitting the form using jQuery like this:
<form actions="http://test.com/" method="GET">
<input name="test" id="autocompleteform" type="text"/>
</form>
<script>
$('#form-customer-attr-new').submit(function(e) {
var value = $("#autocompleteform").val();
value = value.substr(0, value.indexOf(' '));
if (!isNan(value) && !empty(value)) {
$("#autocompleteform").val(value);
alert($("#autocompleteform").val());
return true;
} else {
alert("Invalid Postcode");
return false;
}
});
</script>
when i alert the value of the input file, it's showing the new value, but when the form submitten, the paramether in url still showing the old value of the input, for example:
old_input_value = "1234 justice spoiler message";
new_input_value = "1234";
the_url_after_form_submit_now = "http://test.com?test=1234+justice+spoiler+message";
the_url_after_form_submit_should_be ="http://test.com?test=1234";
<form action="" id="form_id">
<input type="text" name="change_value" id="change_value">
<input type="text" name="d" id="d">
<input type="submit" name="">
</form>
$("#form_id").on("submit", function (e) {
e.preventDefault();//stop submit event
var self = $(this);//this form
$("#change_value").val("deneme");//change input
$("#form_id").off("submit");//need form submit event off.
self.submit();//submit form
});
Couple of things:
id of form was not set, add id="form-customer-attr-new" to form tag
isNan should be isNaN
!empty should be !!
Now it should work. full working example:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no,
initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
</head>
<body>
<form actions="http://test.com/" method="GET" id="form-customer-attr-new">
<input name="test" id="autocompleteform" type="text"/>
<input type="submit" />
</form>
<script>
$('#form-customer-attr-new').submit(function(e) {
var value = $("#autocompleteform").val();
value = value.substr(0, value.indexOf(' '));
if (!isNaN(value) && !!(value)) {
$("#autocompleteform").val(value);
alert($("#autocompleteform").val());
return true;
} else {
alert("Invalid Postcode");
return false;
}
});
</script>
</body>
Here is a slightly different approach, but I believe that it should work.
(1) Create a named function for your logic (I corrected/changed some syntax that was problematic)
<script type="text/javascript" language="javascript">
function prepSubmittal()
{
var result = false;
var value = null;
try
{
value = $("#autocompleteform").val();
if(value.indexOf(" ")>-1) value = value.substring(0, value.indexOf(" "));
if (!isNaN(value) && value.trim().length>0)
{
$("#autocompleteform").val(value);
result = true;
}
else
{
alert("Invalid Postcode");
result = false;
}
}
catch(e)
{
result = false;
alert("prepSubmittal Error: " + e.Message);
}
finally
{
}
return result;
}
</script>
(2) Change your form element to the following (note you had actions attribute instead of action and I added onsubmit="return prepSubmittal()")
<form action="http://test.com" method="GET" onsubmit="return prepSubmittal()">
Let me know how it goes.
You submit the form before you change the value. You have to submit the form using jQuery, after you change the value.
Change the submit button to link to jquery function, change all you have to change and then submit form using:
$("#formId").submit();
To accomplish that you need to:
Prevent form submission
Change input value
submit form with jquery $('#form').submit()
Prevent form submission with e.preventDefault() right inside your callback handler
Use your custom submit via ajax. i.e.,
<form id="form-customer-attr-new" actions="http://test.com/" method="GET">
<input name="test" id="autocompleteform" type="text"/>
</form>
<script>
$('#form-customer-attr-new').submit(function(e) {
var value = $("#autocompleteform").val();
value = value.substr(0, value.indexOf(' '));
var urlPost = 'http://test.com/'
if (!isNan(value) && !empty(value)) {
$("#autocompleteform").val(value);
alert($("#autocompleteform").val());
$.ajax({
type: "GET",
url: urlPost+'?test='+value ,
data: '',
dataType: "text",
success: function(resultData){
alert("Save Complete");
}
} else {
alert("Invalid Postcode");
//return false;
}
});
</script>
Submit API for jQuery
The handler will execute as a response to the $('#form-customer-attr-new').submit() (it's a callback function practically), so you will need to move the code from that function to before you do the actual submit.
So move the code right before the jQuery submit() call.
Also, i see that your id is not added to the HTML, please do that as the call will not work otherwise.
Step 1: call a java script function while form submitted
<form onsubmit="return test();">
Step 2: inside test function set value in your text field.
<script>
function test()
{
document.getElementById("myTextFieldId").value = "12345";
return true;
}
</script>
<form id="form-customer-attr-new" action="" method="get">
<input name="test" id="autocompleteform" type="text" value=""/>
</form>
<script>
$('#form-customer-attr-new').submit(function(e) {
var value = $("#autocompleteform").val();
value = value.substr(0, value.indexOf(' '));
if (!isNaN(value) && value!='') {
$("#autocompleteform").val(value);
alert($("#autocompleteform").val());
return true;
} else {
alert("Invalid Postcode");
return false;
}
});
</script>
I would like to validate myForm, so the user can input a value between 1 and a max on 99. When I submit a number I get showed a blank page, which is the select.php. But I would like to stay on my indexpage, and get the message "You are below". Can anyone see what is wrong here?
index.html:
<div class="content">
<p id="number"></p>
<div class="form">
<form id="myForm" action="select.php" method="post">
<input type="number" name="numbervalue" id="numberinput">
<input type="submit" id="sub" Value="Submit">
<span id="result"></span>
<span id="testnumber"></span>
</form>
</div>
</div>
JS:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#testnumber').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#testnumber').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#testnumber').text('You are above.')
return false;
}
return true;
});
// Insert function for number
function clearInput() {
$("#myForm :input").each( function() {
$(this).val('');
});
}
$(document).ready(function(){
$("#sub").click( function(e) {
e.preventDefault(); // remove default action(submitting the form)
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info){
$("#result").html(info);
});
clearInput();
});
});
// Recieve data from database
$(document).ready(function() {
setInterval(function () {
$('.latestnumbers').load('response.php')
}, 3000);
});
How about utilizing the 'min' and 'max' attributes of the input tag, it would handle all the validation itself:
<input type="number" name="numbervalue" min="1" max="99">
Cheers,
Here's a little function to validate the number:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#result').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#result').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#result').text('You are above.')
return false;
}
return true;
});
You can define the minimum and maximum values by changing the two variables (be sure to check these server-side too if you are submitting to a server, as the user could manipulate the code via dev tools to change these boundaries or submit whatever they want).
The result message is displayed in your span#result, otherwise you could use alert() too.
The important things here are the e parameter in the click function (it's the JavaScript event), calling e.preventDefault() (if you don't do this, the form will submit before finishing validation, as the default action for an input[type=submit] is to submit a form [go figure...]), returning false whenever the conditions aren't met, and returning true if it satisfies the validation. The return true; allows the form to follow its action parameter.
And a fiddle with this: https://jsfiddle.net/3tkms7vn/ (edit: forgot to mention, I commented out return true; and replaced it with a call to add a message to span#result just to prevent submission on jsfiddle.)
I got most of this form validation to work properly but the only issue is that when the form detects an error on submit and the user corrects the mistake, the error text won't go away. This can be confusing for the user but I can't seem to figure out a way to make the error text disappear with the way that I am doing this. Also I know I have the option of PHP validation but there is a few reasons why I want to use this front end validation. Here is the whole validation script for the form. The submit portion is at the bottom:
JavaScript/jQuery
var valid = 0;
function checkName(elem) {
//gather the calling elements value
var val = document.getElementById(elem.id).value;
//Check length
if (val.length<1) {
document.getElementById("errorName").innerHTML = "<span>Don't forget your name.</span>";
} else if (val.length>40){
document.getElementById("errorName").innerHTML = "<span>This doesn't look like a name.</span>";
//If valid input increment var valid.
} else {
document.getElementById("errorName").innerHTML = "";
valid++;
}
}
function checkEmail(elem) {
var val = document.getElementById(elem.id).value;
//Check email format validity
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!re.test(val)) {
document.getElementById("errorEmail").innerHTML = "<span>Please enter a valid email.</span>";
} else {
document.getElementById("errorEmail").innerHTML = "";
valid++;
}
}
function checkMessage(elem) {
var val = document.getElementById(elem.id).value;
if (val.length<1) {
document.getElementById("errorMessage").innerHTML = "<span>It looks like you forgot the message.</span>";
} else if (val.length>2000) {
document.getElementById("errorMessage").innerHTML = "<span>It looks like your message is too long.</span>";
} else {
document.getElementById("errorMessage").innerHTML = "";
valid++;
}
}
//Contact: jQuery check for null/empty/errors
$(document).ready(function() {
function checkSubmit() {
if (valid == 3) {
document.getElementById("errorSubmit").innerHTML = "";
}
}
//If errors when submitting display message
$('#form13').submit(function(submit) {
if ($.trim($("#name").val()) === "" || $.trim($("#email").val()) === "" || $.trim($("#message").val()) === "") {
document.getElementById("errorSubmit").innerHTML = "<span>Please fill out all the form fields.</span>";
submit.preventDefault();
} else if (valid < 3) {
document.getElementById("errorSubmit").innerHTML = "<span>Please check the errors above.</span>";
submit.preventDefault();
}
})
});
HTML Form
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="cform" id="contact-form">
<form id="form13" name="form13" role="form" class="contactForm" accept-charset="UTF-8" autocomplete="off" enctype="multipart/form-data" method="post" novalidate
action="https://Some3rdPartyPOSTService">
<div class="form-group">
<label for="name">Your Name</label>
<input type="text" name="Field1" class="form-control" id="name" placeholder="Tony Stark" onblur="checkName(this)"/>
<span id="errorName" style="margin-left:10px;"></span>
</div>
<div class="form-group">
<label for="email">Your Email</label>
<input type="email" class="form-control" name="Field4" id="email" placeholder="" data-rule="email" data-msg="Please enter a valid email" onblur="checkEmail(this)"/>
<span id="errorEmail" style="margin-left:10px;"></span>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" name="Field3" id="message" rows="5" data-rule="required" data-msg="Please write something here" onblur="checkMessage(this)"></textarea>
<span id="errorMessage" style="margin-left:10px;"></span>
</div>
<span id="errorSubmit" style="margin-left:10px;"></span>
<button type="submit" class="btn btn-theme pull-left">SEND MESSAGE</button>
</form>
</div>
</div>
<!-- ./span12 -->
</div>
</div>
</section>
Simply put your check on onChange event callback, if:
var x = getElementById("formid"); // then add a listener
x.addEventListener('change', function () {
callback with your code that examines the form
});
Or listen for a specific text box change event, that would be the simplest way, and look for a way to disable submit if the conditions aren't met.
Add an onchange event to your text inputs that will remove the error message.
Rather than making a count of valid fields, I would also check for the existence of error messages. This will make it easier to add more fields to your form.
function checkName(e) {
//gather the calling elements value
var val = $(e.target).val();
//Check length
if (val.length<1) {
document.getElementById("errorName").innerHTML = "<span class="errmsg">Don't forget your name.</span>";
} else if (val.length>40){
document.getElementById("errorName").innerHTML = "<span class='errmsg'>This doesn't look like a name.</span>";
//If valid input increment var valid.
} else {
document.getElementById("errorName").innerHTML = "";
}
}
function checkEmail(e) {
var val = $(e.target).val();
//Check email format validity
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!re.test(val)) {
document.getElementById("errorEmail").innerHTML = "<span class='errmsg'>Please enter a valid email.</span>";
} else {
document.getElementById("errorEmail").innerHTML = "";
}
}
function checkMessage(e) {
var val = $(e.target).val();
if (val.length<1) {
document.getElementById("errorMessage").innerHTML = "<span class='errmsg'>It looks like you forgot the message.</span>";
} else if (val.length>2000) {
document.getElementById("errorMessage").innerHTML = "<span class='errmsg'>It looks like your message is too long.</span>";
} else {
document.getElementById("errorMessage").innerHTML = "";
}
}
//Contact: jQuery check for null/empty/errors
$(document).ready(function() {
$('#name').change(checkName);
$('#email').change(checkEmail);
$('#message').change(checkMessage);
function checkSubmit() {
if ($('form .errmsg').length > 0) {
document.getElementById("errorSubmit").innerHTML = "";
}
}
}
/If errors when submitting display message
$('#form13').submit(function(submit) {
if ($.trim($("#name").val()) === "" || $.trim($("#email").val()) === "" || $.trim($("#message").val()) === "") {
document.getElementById("errorSubmit").innerHTML = "<span class='errmsg'>Please fill out all the form fields.</span>";
submit.preventDefault();
} else if ($('form .errmsg').length > 0) {
document.getElementById("errorSubmit").innerHTML = "<span class='errmsg'>Please check the errors above.</span>";
submit.preventDefault();
}
})
});
Since you were already using jQuery, I modified the code to use more of the jQuery functionality to make things easier. Now when a form field is modified and the element loses focus, the validation will occur immediately. We also no longer need to know how many error messages could potentially appear (though you never had a decrement operation for corrected values so the valid could become greater than 3). Instead we just make sure that there isn't more than 0 of them.
I've removed your onblur html attributes and replaced them by JavaScript keyup events. This will allow your script to check everything as soon as the user type something :
document.getElementById("message").addEventListener('keyup', function () {
checkMessage(this);
});
document.getElementById("email").addEventListener('keyup', function () {
checkEmail(this);
});
document.getElementById("name").addEventListener('keyup', function () {
checkName(this);
});
JSFIDDLE