JavaScript Form Validation on submit - javascript

I have a simple form and am validating onchange and need a final validation onsubmit. I am displaying a message to the right of the inputbox on error. I'm trying to keep this at DOM 1 compatible.
HTML
<form id = "myForm" action = "" onsubmit = "return validateForm(this);">
<table class = "table-submit" border = "0">
<tr>
<td>
Username:
</td>
<td>
<input type = "text" id = "username"
size = "30" maxlength = "30"
onchange = "validateUsername(this, 'msgUsername')" />
</td>
<td id = "msgUsername">
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<input type = "password" id = "password"
size = "30" maxlength = "30"
onchange = "validatePassword(this, 'msgPassword')" />
</td>
<td id = "msgPassword">
</td>
</tr>
<tr>
<td> </td>
<td>
<input type = "submit" value = "Submit" />
<input type = "reset" value = "Clear" />
</td>
</tr>
</table>
</form>
JavaScript
function validateUsername(myItem, myElement) {
var dom = document.getElementById(myElement);
if (myItem.value.length < 3) {
dom.innerHTML = " Username needs to be a minimum of 3 characters! ";
return false;
}
else {
dom.innerHTML = "";
return true;
}
}
function validatePassword(myItem, myElement) {
var dom = document.getElementById(myElement);
if (myItem.value.length < 5) {
dom.innerHTML = " Password needs to be a minimum of 5 characters! ";
return false;
}
else {
dom.innerHTML = "";
return true;
}
}
function validateForm (itm) {
// kind of stuck here...
}
As you may of noticed, I am a bit stuck on my validateForm() function.
The code validates on each inputbox onchange event.
Not sure what is the best way to go from here. I thought about doing an If for my both single input box validation, but I would need to send each parameters which is what i was trying to avoid by using this.
Would like some suggestions.

Separate concerns. Instead of having the validate functions not only validate but also report your painting your self into a corner. Instead have a validate function which only returns true/false and another that is your onChange event handler which calls the validate function and displays the error message if needed. Then your onSubmit handler can easily call the validation functions in an if/else block to allow or cancel the submit action.
function validateUsername(username) {
return username.length >= 3;
}
function validatePassword(password) {
return password.length >= 5;
}
function showErrorFn(divId, message) {
var div = document.getElementById(divId);
message = " " + message;
return function(message) {
div.innerHTML = message;
};
}
function makeChangeHandler(myItem, validationFn, errorFn) {
return function(e) {
if (validationFn(myItem.value)) {
return true;
} else {
errorFn();
return false;
}
};
}
function makeSubmitHandler(usernameEl, passwordEl) {
return function(e) {
if (validateUsername(usernameEl.value) && validatePassword(passwordEl.value)) {
return true;
} else {
e.preventDefault();
return false;
}
}
var usernameEl = document.getElementById("username");
var usernameErrorEl = document.getElementById("msgUsername");
usernameEl.addEventListener("change", makeChangeHandler(
usernameEl,
validateUsername,
showErrorFn("Username must be more then 3 characters")
);
var usernameEl = document.getElementById("password");
var usernameErrorEl = document.getElementById("msgPassword");
usernameEl.addEventListener("change", makeChangeHandler(
usernameEl,
validatePassword,
showErrorFn("Password must be more then 5 characters")
);
var formEl = document.getElementById("myForm");
formEl.addEventListener("submit", makeSubmitHandler(usernameEl, password));

You can try this...
function validateForm (itm) {
var flag = true;
flag = (validateUsername(itm.username, 'msgUsername') && flag);
flag = (validatePassword(itm.password, 'msgPassword') && flag);
return flag;
}

Related

Validate empty string in form

I have a form that takes the users input and concatenated that to a url (written in function). How do I check to see if the users value is empty and have an alert appear right below the form that says "Please enter a valid store URL". With out having to re write my entire function! Help!
Input form
<form id="url">
<input type="text" name="urlName">
<button onclick="return myFunction()">Try it</button>
</form>
Javscript Function
document.getElementById("url").addEventListener("submit", myFunction);
function myFunction() {
let myForm = document.getElementById("url");
let formData = new FormData(myForm);
EndOfUrl = sanitizeDomainInput(formData.get("urlName"));
newUrl = redirectLink(EndOfUrl);
window.location.href = newUrl;
return false;
}
function sanitizeDomainInput(input) {
input = input || 'unknown.com'
if (input.startsWith('http://')) {
input = input.substr(7)
}
if (input.startsWith('https://')) {
input = input.substr(8)
}
var regexp = new RegExp(/^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$/)
return regexp.test(input) ? input : 'unknown.com';
}
function redirectLink(domain) {
return `https://dashboard.getorda.com/signup/?state=${domain}`;
}
Check empty string I have not working
function valInput() {
if (input.value.length === 0){
alert("need valid store URL")
}
}
In myFunction you can simple add this code after creating a new instance of FormData:
if (formData.get("urlName") === "")
return alert('asdsa')
It will stop the whole function because of return and will alert you that you haven't put anything in the input box.
Actually, the whole code is kinda wrong
Here's the correct version of javascript code:
document.getElementById("url").addEventListener("submit", (event) => {
event.preventDefault()
let myForm = document.getElementById("url");
let formData = new FormData(myForm);
if (formData.get("urlName").length === 0)
return alert('Provide valid url')
EndOfUrl = sanitizeDomainInput(formData.get("urlName"));
newUrl = redirectLink(EndOfUrl);
window.location.href = newUrl;
return false;
});
function sanitizeDomainInput(input) {
input = input || 'unknown.com'
if (input.startsWith('http://')) {
input = input.substr(7)
}
if (input.startsWith('https://')) {
input = input.substr(8)
}
var regexp = new RegExp(/^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$/)
return regexp.test(input) ? input : 'unknown.com';
}
function redirectLink(domain) {
return `https://dashboard.getorda.com/signup/?state=${domain}`;
}
You call the myFunction twice and you don't even prevenDefault from sending form, so the form is sent whatever you do in the myFunction.
And in HTML you don't need button. You can add input:submit which will trigger function onclick automatically. Here's the correct html code:
<form id="url">
<input type="text" name="urlName">
<input type="submit">
</form>
You can add an onBlur handler to the input.
function validate(val) {
if(val.trim() === "") {
alert("Field is required");
}
}
<input type="text" name="urlName" onblur="validate(this.value)">

Javascript form validation only working once

Script: NewsletterScript.js
function formValidation() {
var fname = document.getElementById('firstName').value;
var lname = document.getElementById('lastName').value;
var pnumber = document.getElementById('phoneNumber').value;
var email = document.getElementById('e-mail').value;
if (FirstName(fname)) {
}
if (LastName(lname)) {
}
if (Country(country)) {
}
if (Email(email)) {
}
return false;
}
/*first name input validation*/
function FirstName(fname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( fname =="" || fname.match(letters)) {
text="";
message[0].innerHTML = text;
return true;
}
else {
text="First name should contain only letters";
message[0].innerHTML = text;
return false;
}
}
/*last name input validation*/
function LastName(lname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( lname =="" || lname.match(letters)) {
text="";
message[1].innerHTML = text;
return true;
}
else {
text="Last name should contain only letters";
message[1].innerHTML = text;
return false;
}
}
I'm trying to get this validation to loop until the criteria is fulfilled, currently this is only working once and if the button is clicked again it submits regardless. Button below.
Due to the script being so long its not letting me upload all of it, however its just got other validation such as phone number etc, Any help will be appreciated, cheers!
If what you want is that formValidation() returns true only when the four validation functions return true you sould write that instead of putting empty if statements :
return FirstName(fname) && LastName(lname) && Country(country) && Email(email);
This manner formValidation() will return false if one of them return false
You should consider using form onsubmit instead on the onclick on the submit button.
Instead of:
<input class="button" type="submit" value="Submit" name="submit" onClick="formValidation()" />
consider using the form submit and do not forget the return keyword:
<form onsubmit="return formValidation();" > /* ... */ </form>
Related Question: HTML form action and onsubmit issues

How to alert user for blank form fields?

I have this form that has 3 inputs and when a user leaves a field blank a dialogue box pops up to alert the user a field is blank. The code I have below only works for 2 specific input. When i try adding another input to the code it doesnt work. It only works for 2 inputs. How can I make it work for all three?
<script type="text/javascript">
function val(){
var missingFields = false;
var strFields = "";
var mileage=document.getElementById("mile").value;
var location=document.getElementById("loc").value;
if(mileage=='' || isNaN(mileage))
{
missingFields = true;
strFields += " Your Google Map's mileage\n";
}
if(location=='' )
{
missingFields = true;
strFields += " Your business name\n";
}
if( missingFields ) {
alert( "I'm sorry, but you must provide the following field(s) before continuing:\n" + strFields );
return false;
}
return true;
}
</script>
Showing 3 alerts may be disturbing, use something like this:
$(document).on('submit', 'form', function () {
var empty = $(this).find('input[type=text]').filter(function() {
return $.trim(this.value) === "";
});
if(empty.length) {
alert('Please fill in all the fields');
return false;
}
});
Inspired by this post.
Or you can do validation for each field this way using HTML data attributes:
<form data-alert="You must provide:" action="" method="post">
<input type="text" id="one" data-alert="Your Google Map's mileage" />
<input type="text" id="two" data-alert="Your business name" />
<input type="submit" value="Submit" />
</form>
... combined with jQuery:
$('form').on('submit', function () {
var thisForm = $(this);
var thisAlert = thisForm.data('alert');
var canSubmit = true;
thisForm.find('input[type=text]').each(function(i) {
var thisInput = $(this);
if ( !$.trim(thisInput.val()) ) {
thisAlert += '\n' + thisInput.data('alert');
canSubmit = false;
};
});
if( !canSubmit ) {
alert( thisAlert );
return false;
}
});
Take a look at this script in action.
Of course, you can select/check only input elements that have attribute data-alert (which means they are required). Example with mixed input elements.
You can add the required tag in the input fields. No jQuery needed.
<input required type="text" name="name"/>
Try this
var fields = ["a", "b", "c"]; // "a" is your "mile"
var empties= [];
for(var i=0; i<fields.length; i++)
{
if(!$('#'+fields[i]).val().trim())
empties.push(fields[i]);
}
if(empties.length)
{
alert('you must enter the following fields '+empties.join(', '));
return false;
}
else
return true;
instead of this
var name = $('#mile').val();
if (!name.trim()) {
alert('you must enter in your mile');
return false;
}

how to generate error message in form if any of the fields left blank

<form onsubmit="chkform()">
<table>
<tr><td>name</td><td><input type="text" id="uname"/></td></tr>
<tr><td></td><td><div id="er1"></div></td></tr>
<tr><td>address</td><td><input type="text" id="add"/></td></tr>
<tr><td></td><td><div id="er2"></div></td></tr>
</table>
</form>
<script>
function chkform()
{
if (document.getElementById("uname").value === "" )
{
document.getElementById("er1").innerHTML = "name cant be left blank";
document.getElementById("er1").style.color = "red";
document.getElementById("er1").style.display = "block";
}
}
</script>
i want to show error message in div, if any of the fields are left blank and this message should disappear when text box is clicked.
Try adding both input boxes to an array, and looping through them to test whether they have values entered or not.
I've edited your code.
function chkform()
{
var inputs = [];
inputs[0] = document.getElementById("uname");
inputs[1] = document.getElementById("add");
for( i =0; i < inputs.length; i++) {
if (inputs[i].value === "" )
{
document.getElementById("er1").innerHTML = "Please fill out all form inputs!";
document.getElementById("er1").style.color = "red";
document.getElementById("er1").style.display = "block";
}
}
}
Using the following will always allow you to add inputs without re-writing your validation function:
function chkform()
{
var form = document.getElementsByTagName('form')[0];
var inputs = form.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++){
if(inputs[i].value === '')
// do your error
}
}
Working fiddle
You should add else part to your if condition, that will take care of removing the error message when thge field has been filled.
else {
document.getElementById("er1").innerHTML = "";
document.getElementById("er1").style.display = "none";
}
http://codepen.io/anon/pen/gxJid
I guess you need return to
<form onsubmit="return chkform()">
and
return false in your red alert message block
that works.
i.e.
<form onsubmit="return chkform()">
function chkform() {
if (document.getElementById("uname").value === "") {
. . .
return false;
}
if (document.getElementById("car").value == "truck") {
. . .
return false;
}
. . .
}
<form onsubmit="return false">
<table>
<tr><td>name</td><td><input type="text" id="uname"/></td></tr>
<tr><td></td><td><div id="er1"></div></td></tr>
<tr><td>address</td><td><input type="text" id="add"/></td></tr>
<tr><td></td><td><div id="er2"></div></td></tr>
</table>
<input type="submit" onclick="chkform()"/>
</form>
<script>
function chkform()
{
if (document.getElementById("uname").value === "" )
{
document.getElementById("er1").innerHTML = "name cant be left blank";
document.getElementById("er1").style.color = "red";
document.getElementById("er1").style.display = "block";
}
}
</script>

How to hide/show messages in javascript when they should be hidden/shown?

I have a code below where it contains a form which contains text inputs a drop down menu:
$editsession = "
<form id='updateCourseForm'>
<p><strong>Current Course Details:</strong></p>
<table>
<tr>
<th>Course ID:</th>
<td><input type='text' id='currentCourseNo' name='CourseNocurrent' readonly='readonly' value='' /> </td>
</tr>
</table>
<div id='currentAlert'></div>
<p><strong>New Course Details:</strong></p>
<table>
<tr>
<th>Course ID:</th>
<td><input type='text' id='newCourseNo' name='CourseNoNew' value='' /> </td>
</tr>
</table>
<div id='newAlert'></div>
</form>
<p id='submitupdatebtn'><button id='updateSubmit'>Update Course</button></p>
";
echo $editsession;
Now I want to validate the form using Javascript and below is the code for the javascript validation:
function editvalidation() {
var isDataValid = true;
var currentCourseO = document.getElementById("currentCourseNo");
var newCourseNoO = document.getElementById("newCourseNo");
var currentCourseMsgO = document.getElementById("currentAlert");
var newCourseMsgO = document.getElementById("newAlert");
if (currentCourseO.value == ""){
currentCourseMsgO.innerHTML = "Please Select a Course to edit from the Course Drop Down Menu";
$('#newAlert').hide();
isDataValid = false;
}else{
currentCourseMsgO.innerHTML = "";
}
if (newCourseNoO.value == ""){
newCourseMsgO.innerHTML = "Please fill in the Course ID in your Edit";
$('#newAlert').show();
isDataValid = false;
} else{
newCourseMsgO.innerHTML = "";
}
return isDataValid;
}
Now this is the problem I am getting:
What I am trying to state in my javascript validation is that if the #currentCourseNo is empty (text input is blank), then it displays the error message for this which belongs to the div tag #currentAlert, but it hides messages which are displayed in the div tag #newAlert. If the #currentCourseNois not empty then show the #newAlert error messages if there are any.
The problem I am having is that it is still showing the #newAlert error messages when the #currentCourseNo text input is empty, when it really should be hidden. What needs to be changed in the javascript above in order to achieve what I want to achieve?
First, learn about jQuery.
For your process, my common flow is to add a first pass of validation on the blur event of the inputs, and a second (exactly the same) pas of validation on the submit event of the form, something like :
var error = $('.errormsg');
var checks =
{
"fieldName1": function(val) { return /*true or an error string*/ },
"fieldName2": function(val) { return /*true or an error string*/ }
};
$('input')
.focus(function()
{
$(this).removeClass('error');
})
.blur(function()
{
error.slideUp(200);
var check = checks[this.name];
if (!check) { return; }
var validation = check(this.value);
if (typeof validation === "string")
{
$(this).addClass('error');
error.text(validation).slideDown(200);
}
});
$('form').submit(function(e)
{
//e.preventDefault();
if ($('input.error').length != -1)
{
error.text('All fields are required').slideDown(200);
return;
}
for(var check in checks)
{
var field = $('input[name="' + check + '"]');
if (field.length == -1) { continue; }
var validation = check(field.val());
if (typeof validation === "string")
{
field.addClass('error');
error.text(validation).slideDown(200);
return;
}
}
});

Categories

Resources