JavaScript form validation on server/local - javascript

I'm using JavaScript form validation for the entry form for a contest I'm running. It's inline CSS so that if certain conditions aren't met, it displays, in red, messages that say "please enter your email address" or "that doesn't look like a valid email address" etc.
The script, which sits at the top of the file, looks like this:
<script>
function checkForm() {
name = document.getElementById("name").value;
email = document.getElementById("email").value;
terms = document.getElementById("terms").value;
if (name == "") {
hideAllErrors();
document.getElementById("nameError").style.display = "inline";
document.getElementById("name").select();
document.getElementById("name").focus();
return false;
} else if (email == "") {
hideAllErrors();
document.getElementById("emailError").style.display = "inline";
document.getElementById("email").select();
document.getElementById("email").focus();
return false;
}
else if (!check_email(document.getElementById("email").value)) {
hideAllErrors();
document.getElementById("emailError2").style.display = "inline";
document.getElementById("email").select();
document.getElementById("email").focus();
return false;
}
else if (!document.form1.terms.checked){
hideAllErrors();
document.getElementById("termsError").style.display = "inline";
document.getElementById("terms").select();
document.getElementById("terms").focus();
return false;
}
return true;
}
function check_email(e) {
ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.#-_QWERTYUIOPASDFGHJKLZXCVBNM";
for(i=0; i < e.length ;i++){
if(ok.indexOf(e.charAt(i))<0){
return (false);
}
}
if (document.images) {
re = /(#.*#)|(\.\.)|(^\.)|(^#)|(#$)|(\.$)|(#\.)/;
re_two = /^.+\#(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!e.match(re) && e.match(re_two)) {
return (-1);
}
}
}
function hideAllErrors() {
document.getElementById("nameError").style.display = "none"
document.getElementById("emailError").style.display = "none"
document.getElementById("commentError").style.display = "none"
document.getElementById("termsError").style.display = "none"
}
The email and name validation work just fine, the part of the form that won't work looks like this:
<form onSubmit="return checkForm();" method="get" action="sweepstakes-results.php"
<input type=checkbox name=terms id=terms ><br></p>
<div class=error id=termsError>Required: Please check the checkbox<br></div>
<p><input type=submit value=Send style="margin-left: 50px"> </p>
</form>
The "terms and conditions" checkbox only works if the file is on my local machine, when I upload it, it just lets me submit the form even if it's not checked. Isn't JavaScript run on the browser? How could the location of the file make a difference?

Your form doesn't have a name, so the following code won't work:
else if (!document.form1.terms.checked){
Since you're already retrieving the DOM object of the checkout, do the following. Change the line:
terms = document.getElementById("terms").value;
to:
terms = document.getElementById("terms");
And the replace that else if code with:
else if (!terms.checked){

Related

Remove form error with correct input

I just made a registration form which will tell you in red(CSS) letters if something is wrong. However I want this text to go away as soon as the user writes it correctly. How do I do that?
<script>
function validateForm2() {
var usrnm2 = document.getElementById("usrnm2").value;
var passw2 = document.getElementById("passw2").value;
var cnfpassw2 = document.getElementById("cnfpassw2").value;
var age = document.getElementById("age").value;
if (usrnm2 == null || usrnm2 == "") {
document.getElementById("error1").innerHTML = "You must enter a username";
return false;
}
else if (passw2 == null || passw2 == "") {
document.getElementById("error2").innerHTML = "You must enter a password";
return false;
}
else if (cnfpassw2 !== passw2) {
document.getElementById("error3").innerHTML = "Password does not match";
return false;
}
else if (age < 18) {
document.getElementById("error4").innerHTML = "You are not old enough to enter this site"
return false;
}
else {
alert("Congratulations, you have registered successfully!")
}
}
</script>
<script>
function register2() {
validateForm2()
}
</script>
<form>
Username:
<input id="usrnm2" type="text" name="username"><p id="error1"></p>
Password
<input id="passw2" type="password" name="password"><p id="error2"></p>
Confirm Password
<input id="cnfpassw2" type="password" name="confirmpw2"><p id="error3"></p>
Age
<input id="age" type="number" name="age"><p id="error4"></p><br />
<input id="bttn2" type="button" value="Register!" onclick="register2()"><br />
</form>
Separate the validation conditions into single block if statements, and then include a handler for returning the fields to normal when they are entered correctly:
if (field is entered incorrectly) {
document.getElementById("error").innerHTML = "You must enter correctly";
return false;
}
else {
document.getElementById("error").innerHTML = "";
}
...
alert("Congratulations, you have registered successfully!");
You simply need to place the alert after all of the statements - it will execute as long as none of the conditions fail and thus return.

Return false does not prevent form submission

I have form that I need to validate using JavaScript and I need to show all the messages at the same time. E.g if the first name and surename is missing for two messages to appear. I've got this working with the below code but the form is still being returned back to the server. P Lease see below:
function validateForm() {
var flag = true;
var x = document.forms["myForm"]["firstname_4"].value;
if (x == null || x == "") {
document.getElementById("fNameMessage").innerHTML = "First name is required";
flag = false;
} else {
document.getElementById("fNameMessage").innerHTML = "";
}
var x = document.forms["myForm"]["surname_5"].value;
if (x == null || x == "") {
document.getElementById("sNameMessage").innerHTML = "Surename is required";
flag = false;
} else {
document.getElementById("sNameMessage").innerHTML = "";
}
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title") {
document.getElementById("titleMessage").innerHTML = "You need to select a title";
flag = false;
} else {
document.getElementById("titleMessage").innerHTML = "";
}
return flag;
}
My form and event :
<form action=""method="post" accept-charset="UTF-8" name="myForm" onsubmit="return validateForm();">
My Button:
<input type="submit" class="button" name="submit" id="submit" value="Submit">
Your code:
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title")
... triggers an exception and you don't catch it:
Uncaught TypeError: Cannot read property 'options' of undefined
Thus JavaScript code stops running.
Since everyone seems to be providing jQuery answers and I didn't see anything in your orignal code that was jQuery-esque I'll assume you aren't using jQuery.
You should be using the event.preventDefault:
Sources:
https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement.submit
document.getElementById("submit").addEventListener(
"click", validateForm, false
);
function validateForm(){
// We should not assume a valid form!
var formValid = false;
// All your validation code goes here
if(formValid){
document.forms["myform"].submit();
}
}
try something like
if(flag){
document.getElementById("submit").submit();
}
else{
$('#submit').click(function (e) {
e.preventDefault();
});
}

Form validation onblur() doesn't work

I have this javascript code (the function SHA-1 is located in an external file):
window.onload = validatePass;
function validatePass() {
var el = document.getElementById("oriPass");
var user_pass = el.value;
var hashed_pass = SHA1(user_pass);
var span = document.createElement("span");
el.parentNode.appendChild(span);
el.onblur = function doSomething() {
if(user_pass == null || user_pass == "") {
span.setAttribute('class','required');
span.innerHTML="this is a required field";
}
else {
if(hashed_pass != '7c4a8d09ca3762af61e59520943dc26494f8941b') {
span.setAttribute('class','required');
span.innerHTML="wrong password";
}
else {
span.setAttribute('class','required_ok');
span.innerHTML="valid password";
}
}
}
}
and this in html:
<form name="form" method="post" action="change_pass.php">
<div class="row">
<div class="col1">write your password:<span class="required">*</span></div>
<div class="col2">
<input type="password" name="original_pass" id="oriPass" />
</div>
</div>
</form>
For some reason, every time I test it I get the same output: "valid password", no matter if the field is empty, valid or invalid.
What am I doing wrong here?
move the var user_pass... and var hashed_pass... code inside the onblur function. Now the are assigned only onload and will never change. Also it might be better to use onchange instead of onblur.
window.onload = validatePass;
function validatePass() {
var el = document.getElementById("oriPass");
var span = document.createElement("span");
el.parentNode.appendChild(span);
el.onchange = function doSomething() {
var user_pass = el.value;
var hashed_pass = SHA1(user_pass);
if(user_pass == null || user_pass == "") {
span.setAttribute('class','required');
span.innerHTML="this is a required field";
}
else {
if(hashed_pass != '7c4a8d09ca3762af61e59520943dc26494f8941b') {
span.setAttribute('class','required');
span.innerHTML="wrong password";
}
else {
span.setAttribute('class','required_ok');
span.innerHTML="valid password";
}
}
}
}
You are setting the variable for password only on load. It never changes after that. You need to set it inside the onblur function.

Submitting a form with onclick and onsubmit

I'm trying to setup a 'Click to Chat' system for my company. It requires a form which captures some information from the user. When you submit the form, it's supposed to open a new window using the script in the .js file.
I tried to add some validation, which resulted in both an onclick, and an onsubmit function. When the form is subitted without the validation in place, it opens a new window using the BG.startChatWithIssueForm(this.form, true); function. But, For some reason, when I include the onsubmit for validation, the onclick ignores it completely.
I've tried nesting the BG.startChatWithIssueForm(this.form, true); function in different spots in the formValidator() function, but it still results in a file download prompt instead of opening a new window.
Not sure what I'm doing wrong. I've been researching this for weeks, and can't seem to come up with anything. Javascript is definitely not my forte, so any assistance would be greatly appreciated.
See the code below:
JS:
function Bomgar() {
var _host = "";
var _protoRe = /^(http|https):\/\//;
/* private */
function _createURL(params, forPopup) {
var qStr = "";
for (var k in params) {
qStr += "&"+encodeURIComponent(k)+"="+encodeURIComponent(params[k]);
}
qStr = "popup="+(forPopup ? "1" : "0") + "&c2cjs=1" + qStr;
return _host+"api/start_session.ns?"+qStr;
};
function _openWindow(params) {
return window.open(_createURL(params, true), 'clickToChat', 'toolbar=no,directories=no,status=no,menubar=no,resizable=yes,location=no,scrollbars=no');
};
function _redirectWindow(params) {
window.location.href = _createURL(params, false);
};
function _startChat(params, doFull) {
var w = _openWindow(params);
if (w && !w.closed) { return; }
else if (doFull) { _redirectWindow(params); return; }
};
function _startChatWithSurveyValues(surveyValues, fallbackToFullWindow) {
surveyValues.issue_menu = '1';
_startChat(surveyValues, fallbackToFullWindow);
};
/* public */
// Set the public site hostname that click to chat should be started on.
this.setSite = function(siteHostname) {
if (!_protoRe.test(siteHostname)) { siteHostname = "http://"+siteHostname; }
if (siteHostname[siteHostname.length-1] != '/') { siteHostname += '/'; }
_host = siteHostname;
};
// Start a click to chat session using a session key, optionally falling back to a full browser window redirect if the popup window fails to open due to popup blockers.
this.startChatWithSessionKey = function(sessionKey, fallbackToFullWindow) {
var p = {short_key: sessionKey};
_startChat(p, fallbackToFullWindow);
};
// Start a click to chat session using a session key and external key, optionally falling back to a full browser window redirect if the popup window fails to open due to popup blockers.
this.startChatWithSessionKeyAndExternalKey = function(sessionKey, externalKey, fallbackToFullWindow) {
var p = {short_key: sessionKey, external_key: externalKey};
_startChat(p, fallbackToFullWindow);
};
// Start a click to chat session using just an issue id and no other front end survey fields.
this.startChatWithIssueId = function(issueId, fallbackToFullWindow) {
_startChatWithSurveyValues({id: issueId}, fallbackToFullWindow);
};
// Start a click to chat session by passing the entire front end survey form element.
// This will submit all non-button input element values on the form.
// Any unexpected survey field names will be ignored.
this.startChatWithIssueForm = function(formElement, fallbackToFullWindow) {
var params = {};
for (var i = 0; i < formElement.elements.length; i++) {
var e = formElement.elements[i];
if (e.name && e.value && e.type && e.type != 'button' && e.type != 'submit') {
params[e.name] = e.value;
}
}
formElement = undefined;
params.issue_menu = '1';
_startChat(params, fallbackToFullWindow);
return false;
};
// Start a session with a representative id and name.
this.startChatWithRepIdName = function(repId, repName, fallbackToFullWindow) {
var p = {id: repId, name: repName};
_startChat(p, fallbackToFullWindow);
};
return this;
}
var BG = Bomgar();
HTML Code:
<script type="text/javascript" src="https://***.******.com/api/clicktochat.js"></script>
<script type="text/javascript">
BG.setSite("https://***.******.com");
</script>
<script type='text/javascript'>
function formValidator(){
// Make quick references to our fields
var issueid = document.getElementById('issueid');
var username = document.getElementById('username');
var userid = document.getElementById('userid');
var issuedesc = document.getElementById('issuedesc');
// Check each input in the order that it appears in the form
if(madeSelection(issueid, "Please choose an issue"))
{
if(notEmpty(username, "Please enter your name"))
{
if(isAlphanumeric(username, "Numbers and Letters Only for name"))
{
if(notEmpty(userid, "Please enter your user ID"))
{
if(isAlphanumeric(userid, "Numbers and Letters Only for user ID"))
{
if(notEmpty(issuedesc, "Please type a description of your problem"))
{
}
}
}
}
}
}
}
//check to make sure user selected their issue
function madeSelection(elem, helperMsg){
if(elem.selectedIndex == 0 ){
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}else{
return true;
}
}
//check to make sure user entered something in the particular field
function notEmpty(elem, helperMsg){
if(elem.value.length == 0){
alert(helperMsg);
elem.focus();
return false;
}else{
return true;
}
}
//check to make sure user only entered numeric characters
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
//check to make sure user only entered alpha characters
function isAlphabet(elem, helperMsg){
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
//check to make sure user entered only alpha or numeric characters
function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
</script>
<script type="text/javascript">
/***********************************************
* Disable "Enter" key in Form script- By Nurul Fadilah(nurul#REMOVETHISvolmedia.com)
* This notice must stay intact for use
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/
function handleEnter (field, event) {
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if (keyCode == 13) {
var i;
for (i = 0; i < field.form.elements.length; i++)
if (field == field.form.elements[i])
break;
i = (i + 1) % field.form.elements.length;
field.form.elements[i].focus();
return false;
}
else
return true;
}
</script>
<form action="https://***.******.com/api/start_session.ns" onsubmit="return formValidator();" method="get">
What issue are you having?
<select onkeypress="return handleEnter(this, event)" id="issueid" name="id">
<option value="">Choose</option>
<option value="1">I need help getting started</option>
<option value="2">I am receiving an error</option>
</select>
<br />
Your First and Last Name: <input onkeypress="return handleEnter(this, event)" type="text" id="username" name="customer_name" /><br />
Your User ID (ABC1234): <input onkeypress="return handleEnter(this, event)" type="text" id="userid" name="customer_id" /><br />
Describe Your Issue: <textarea onkeypress="return handleEnter(this, event)" id="issuedesc" name="customer_desc"></textarea><br />
<input onkeypress="return handleEnter(this, event)" type="hidden" name="issue_menu" value="1" />
<input onkeypress="return handleEnter(this, event)" type="submit" value="Submit" onclick="BG.startChatWithIssueForm(this.form, true); return false;" />
<br>
<input onkeypress="return handleEnter(this, event)" type="button" name="reset_form" value="Clear" onclick="this.form.reset();">
</form>
</body>
Have you tried replacing the submit button with a regular button, doing the validation in the onClick handler, and then submitting the form from within the onClick handler?
Edit: e.g. replace
<input onkeypress="return handleEnter(this, event)" type="submit" value="Submit" onclick="BG.startChatWithIssueForm(this.form, true); return false;" />
with
<input onkeypress="return handleEnter(this, event)" type="button" value="Submit" onclick="BG.handleSubmit(this.form, true);" />
Then maybe use a Javascript function like this (I'm not sure exactly what order you want these things to happen in):
BG.handleSubmit = function(formElement, fallBackToFullWindow) {
if (!formValidator())
return;
BG.startChatWithIssueForm(formElement, fallBackToFullWindow);
formElement.submit();
return false;
}
Edit: Your validation function should probably return false if it finds something invalid.
function formValidator(){
// Make quick references to our fields
var issueid = document.getElementById('issueid');
var username = document.getElementById('username');
var userid = document.getElementById('userid');
var issuedesc = document.getElementById('issuedesc');
var valid = true;
// Check each input in the order that it appears in the form
if(!madeSelection(issueid, "Please choose an issue"))
valid = false;
if(!notEmpty(username, "Please enter your name"))
valid = false;
if(!isAlphanumeric(username, "Numbers and Letters Only for name"))
valid = false;
if(!notEmpty(userid, "Please enter your user ID"))
valid = false;
if(!isAlphanumeric(userid, "Numbers and Letters Only for user ID"))
valid = false;
if(!notEmpty(issuedesc, "Please type a description of your problem"))
valid = false;
return valid;
}

serverclick event is not fired when onclick javascript returns true?

I have a html input button like this
<input type="button" id="send_button" class="form_button" value="Send" onclick="return validateTextBoxes();" runat="server" />
And also I have javascript
<script language="javascript">
function validateTextBoxes()
{
var reading1 = document.getElementById('<%= meterReading1.ClientID%>').value;
var error = document.getElementById('<%= lblError.ClientID%>');
var btn = document.getElementById('<%= send_button.ClientID%>');
var ValidationExpression = /[\d]/;
if (reading1 == "" )
{
error.innerHTML = "Please enter Water Meter Reading.";
return false;
}
else if(!ValidationExpression.test(reading1)) {
error.innerHTML = "Please enter valid Meter Reading(It Contains only numbers)";
return false;
}
else
{
error.innerHTML = "";
return true;
}
}
</script>
And I am also calling this server click event in the code behind file
this.send_button.ServerClick += new System.EventHandler(this.send_ok);
So here is the problem when javscript returns true its not firing the serverclick event.
Please help me where I am doing wrong(I am using framework 1.1)
Thanks
I had this problem once and I actually had to do something like this:
onclick="if (validateTextBoxes()) { return true; } else { return false; }"
You absolutely should not have to do this and it made no sense to me why it would be have this way, but alas, I tried it and it worked :(

Categories