<script>
$(document).ready(function() // Run the function after the DOM is ready
{
var validForm = true; // Set the variable to be true, assume the form is valid
// Required field. Cannot be empty, spaces, null or undefinded. Contents of the field cannot contain < or > or '.
function validateName()
{
var nameInput = $("#custName").val(); // Create a variable that takes in the value of the field
var nameEx = new RegExp(/<>^[a-zA-Z0-9]*$/); // RegEx of what the field should contain
var nameTest = nameEx.test(nameInput); // Test the RegEx with the current input
if(nameInput == "")
{
nameTest = false;
validForm = false; // Form will be set to false
var custNameError = $("#custNameError").html("Please enter a valid name");
}
else if (nameInput != "" && !nameTest)
{
nameTest = false;
validForm = false;
custNameError = $("#custNameError").html("Please enter a valid name");
}
else
{
custNameError = $("#custNameError").html("");
}
};
// Field is optional. Must be numbers only
function validatePhone()
{
var phoneInput = $("#custPhone").val();
var phoneEx = new RegExp(/^[0-9]{10}$/); // 10 digit RegEx from 0-9
if(phoneEx.test(phoneInput))
{
$("#custPhoneError").html("Please enter a valid 10 digit phone number");
validForm = false;
}
else
{
validForm = true;
}
};
// Required field. Can have letters, numbers, symbols, and including # and . email address.
function validateEmail()
{
var emailInput = $("#custEmail").val;
var emailEx = new RegExp (/^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$/);
var emailTest = emailEx.text(emailInput);
var custEmailError = $("#custEmailError").html("");
if(!emailTest)
{
validForm = false;
if(emailInput == "")
{
custEmailError = $("#custEmailError").html("Please enter a valid email address.");
}
else
{
if(emailInput != "" && !emailTest)
{
custEmailError = $("#custEmailError").html("Please enter a valid email in the following format: test123#email.com");
$("#custEmail").val(emailInput);
validForm = true;
}
}
}
};
// Required field. Must select one radio button
function validateProduct()
{
var productInput = $("input[type=radio]:checked").val();
if (productInput == undefined)
{
var productTest = false;
validForm = false;
var custProductError = $("#custProductError").html("Please select a product in regards to your complaint");
}
else if (!validForm)
{
$("input[type=radio]:checked").val(productInput);
}
else
{
productTest = true;
custProductError = $("#custProductError").html("");
validForm = true;
}
};
// Required field. Must be longer than 5 characters, can contain basic punctuation symbols
function validateComplaint()
{
var complaintInput = $("#custComplaint").val();
var complaintEx = new RegExp (/^[a-zA-Z0-9,.!?;" ]{5,}$/);
var complaintTest = complaintEx.test(complaintInput);
var complainLengthInput = complaintInput.length;
if (complainLengthInput < 5)
{
validForm = false;
var custComplaintError = $("#custComplaintError").html("Please have your complaint to be at least 5 characters long");
$("#custComplaint").val(complaintInput);
}
else if (complaintTest)
{
custComplaintError = $("#custComplaintError").html("");
}
else
{
if (complainLengthInput >= 5 && !complaintTest)
{
custComplaintError = $("#custComplaintError").html("Please describe your complaint in detail. Using letters and numbers.")
$("#custComplaint").val(complaintInput);
}
else
{
validForm = true;
}`enter code here`
}
};
function submitForm()
{
$("#sendForm").click(function()
{
validateName();
validateEmail();
validatePhone();
validateProduct();
validateComplaint();
});
$("#resetForm").click(function()
{
$("#custNameError").html("");
$("#custPhoneError").html("");
$("#custEmailError").html("");
$("#custProductError").html("");
$("#custComplaintError").html("");
});
};
});
HTML:
<h2>WDV321 Advanced Javascript </h2>
<h3>Form Validation Project - Complaint Form</h3>
<form id="form1" name="form1" method="post" action="">
<p>Please enter the following information in order to process your concerns.</p>
<p>
<label for="custName">Name:</label>
<input type="text" name="custName" id="custName" />
<span id="custNameError" class="errorMsg"></span>
</p>
<p>
<label for="custPhone">Phone Number: </label>
<input type="text" name="custPhone" id="custPhone" />
<span id="custPhoneError" class="errorMsg"></span>
</p>
<p>
<label for="custEmail">Email: </label>
<input type="text" name="custEmail" id="custEmail" />
<span id="custEmailError" class="errorMsg"></span>
</p>
<p>Please Select Product Group:</p>
<span class="error" id="custProductError"></span>
<p>
<label>
<input type="radio" name="custProducts" value="books" id="custProducts_0" />
Books</label>
<br />
<label>
<input type="radio" name="custProducts" value="movies" id="custProducts_1" />
Movies</label>
<br />
<label>
<input type="radio" name="custProducts" value="electronics" id="custProducts_2" />
Consumer electronics</label>
<br />
<label>
<input type="radio" name="custProducts" value="computer" id="custProducts_3" />
Computer</label>
<br />
</p>
<p>Description of problem: (Limit 200 characters)</p>
<span class="error" id="custComplaintError"></span>
<p>
I am extremely confused on what I am doing wrong. When the submit button is hit, it doesn't seems like its running any of my functions. The console on google chrome isnt giving me any errors, and from what I am reviewing, it doesnt seem like I see any syntax errors. Please advise.
function submitForm(e) // grab the click event
{
e.preventDefault(); // prevent default event
$("#sendForm").click(function()
{
validateName();
validateEmail();
validatePhone();
validateProduct();
validateComplaint();
});
$("#resetForm").click(function()
{
$("#custNameError").html("");
$("#custPhoneError").html("");
$("#custEmailError").html("");
$("#custProductError").html("");
$("#custComplaintError").html("");
});
};
Related
I would like to show tick simple when the field is filled correctly, and show error message when it is not filled on each field.
I tried to make the code which using function validateForm, but it did not work. How do I fix the code? Please teach me where to fix.
Here is my html code
<form>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Name</p>
<input type="text"id="name">
</div>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required" >Required</span>Number</p>
<input type="text" id="number">
</div>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Mail address</p>
<input type="email">
</div>
<div class="Form-Item">
<p class="Form-Item-Label isMsg"><span class="Form-Item-Label-Required">Required</span>Message</p>
<textarea id="text"></textarea>
</div>
<input type="submit" value="submit">
<p id="log"></p>
</form>
Here is my JavaScript code
function validateForm(e) {
if (typeof e == 'undefined') e = window.event;
var name = U.$('name');
var number = U.$('number');
var email = U.$('email');
var text = U.$('text');
var error = false;
if (/^[A-Z \.\-']{2,20}$/i.test(name.value)) {
removeErrorMessage('name');
addCorrectMessage('name', '✔');
} else {
addErrorMessage('name', 'Please enter your name.');
error = true;
}
if (/\d{3}[ \-\.]?\d{3}[ \-\.]?\d{4}/.test(number.value)) {
removeErrorMessage('number');
addCorrectMessage('number', '✔');
} else {
addErrorMessage('number', 'Please enter your phone number.');
error = true;
}
if (/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,6}$/.test(email.value)) {
removeErrorMessage('email');
addCorrectMessage('email', '✔');
} else {
addErrorMessage('email', 'Please enter your email address.');
error = true;
}
if (/^[A-Z \.\-']{2,20}$/i.test(text.value)) {
removeErrorMessage('text');
addCorrectMessage('text', '✔');
} else {
addErrorMessage('text', 'Please enter your enquiry.');
error = true;
}
if (error) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
return false;
}
}
function addErrorMessage(id, msg) {
'use strict';
var elem = document.getElementById(id);
var newId = id + 'Error';
var span = document.getElementById(newId);
if (span) {
span.firstChild.value = msg;
} else {
span = document.createElement('span');
span.id = newId;
span.className = 'error';
span.appendChild(document.createTextNode(msg));
elem.parentNode.appendChild(span);
elem.previousSibling.className = 'error';
}
}
function addCorrectMessage(id, msg) {
'use strict';
var elem = document.getElementById(id);
var newId = id + 'Correct';
var span = document.getElementById(newId);
if (span) {
span.firstChild.value = msg;
} else {
span = document.createElement('span');
span.id = newId;
span.className = 'Correct';
span.appendChild(document.createTextNode(msg));
elem.parentNode.appendChild(span);
elem.previousSibling.className = 'Correct';
}
}
function removeErrorMessage(id) {
'use strict';
var span = document.getElementById(id + 'Error');
if (span) {
span.previousSibling.previousSibling.className = null;
span.parentNode.removeChild(span);
}
}
function removeCorrectMessage(id) {
'use strict';
var span = document.getElementById(id + 'Correct');
if (span) {
span.previousSibling.previousSibling.className = null;
span.parentNode.removeChild(span);
}
}
Using jQuery, you can use the .submit() event on a form element to conduct your own validation, note that you will have to preventDefault() to prevent the form submitting.
$("#myform").submit((e) => {
e.preventDefault(e);
// Validate name.
const name = $("#name").val();
if (name.length === 0) {
alert("Please provide a name!");
return;
}
alert("Success!");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<input type="text" id="name" placeholder="John Doe" />
<button type="submit">Submit</button>
</form>
which npm package do u use to validate ur data?.
If u use "validator" (link: https://www.npmjs.com/package/validator)
You can check if the field is filled correctly and send a check mark to the user.
for example if u wanted to check if data is an email
const validator = require("validator");
validator.isEmail('foo#bar.com');
if u want to see more about the options for the field just check the npm package page
Modern Browser support the Constraint Validation API which provides localized error messages.
Using this you can easily perform validation during basic events. For example:
// this will prevent the form from submit and print the keys and values to the console
document.getElementById("myForm").onsubmit = function(event) {
if (this.checkValidity()) {
[...new FormData(this).entries()].forEach(([key, value]) => console.log(`${key}: ${value}`);
event.preventDefault();
return false;
}
}
Would print all fields which would've been submitted to the console.
Or on an input field:
<input type="text" pattern="(foo|bar)" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());">
Will add the css class "valid" to the input field parent, if the value is foo or bar.
.valid {
border: 1px solid green;
}
.valid::after {
content: '✅'
}
<form oninput="this.querySelector('#submitButton').disabled = !this.checkValidity();" onsubmit="event.preventDefault(); console.log('Submit prevented but the form seems to be valid.'); return false;">
<fieldset>
<label for="newslettermail">E-Mail</label>
<!-- you could also define a more specific pattern on the email input since email would allow foo#bar as valid mail -->
<input type="email" id="newslettermail" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
</fieldset>
<fieldset>
<input type="checkbox" id="newsletterAcceptTos" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
<label for="newsletterAcceptTos">I accept the Terms of Service</label>
</fieldset>
<fieldset>
<label for="textFieldWithPattern">Enter <strong>foo</strong> or <strong>bar</strong></label>
<input type="text" id="textFieldWithPattern" pattern="^(foo|bar)$" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" >
</fieldset>
<button type="submit" id="submitButton" disabled>Submit</button>
<button type="submit">Force submit (will show errors on invalid input)</button>
</form>
here is my working code on password field validation check. it works fine while all criterion are met but when it doesn't it gets stuck on last validation checks in case of submitting form after validation completions!!
Please have a look [here][1]
[1]: https://codepen.io/bappyasif/pen/vYNoEap?editors=1112
var firstPasswordInput = document.querySelector("#first");
var secondPasswordInput = document.querySelector("#second");
var submit = document.querySelector("#submit");
let symbolPattern = /[\!\#\#\$\%\^\&\*]/g;
let numberPattern = /\d/g;
let lowercasePattern = /[a-z]/g;
let uppercasePattern = /[A-Z]/g;
let unallowedCharacters = /[^A-z0-9\!\#\#\$\%\^\&\*]/g;
submit.onclick = function () {
let firstPassword = firstPasswordInput.value;
let secondPassword = secondPasswordInput.value;
if (firstPassword === secondPassword && firstPassword.length > 0) {
checkRequirements();
} else {
secondPasswordInput.setCustomValidity("Passwords must match!");
}
function checkRequirements() {
if (firstPassword.length < 6) {
firstPasswordInput.setCustomValidity("Fewer than 6 characters");
// return;
} else if (firstPassword.length >= 10) {
firstPasswordInput.setCustomValidity("greater than 10 characters");
// return;
}
// Pattern Checks
if (!firstPassword.match(symbolPattern)) {
firstPasswordInput.setCustomValidity(
"missing a symbol (!, #, #, $, %, ^, &, *"
);
if (!firstPassword.match(numberPattern)) {
firstPasswordInput.setCustomValidity("missing a number");
// return false;
// return;
}
if (!firstPassword.match(lowercasePattern)) {
firstPasswordInput.setCustomValidity("missing a lowercase letter");
// return;
}
if (!firstPassword.match(uppercasePattern)) {
firstPasswordInput.setCustomValidity("missing an uppercase letter");
// return;
}
if (firstPassword.match(unallowedCharacters)) {
firstPasswordInput.setCustomValidity("includes illegal character: ");
// return;
}
}
}
};
Form Related HTML Tags For Shared Code Snippet:
<label>
<input id="first" type="password" placeholder="New password" autofocus maxlength="100" required />
</label>
<!-- type="password" -->
<label>
<input id="second" type="password" placeholder="Repeat password" autofocus maxlength="100" required />
</label>
<input id="submit" type="submit" />
Hope, you all doing well.
I am trying to validate firstname input field of a form with Javascript. For some reason, error messages doesn't display in order. Some of them override others, only just one error message is displaying, the rest is not.
I'm wondering why? Can anyone shed me some light please?
Here is my code:
// Predefined validator function to check if input is empty or not
var validator = {};
validator.isEmpty = function(input) {
// Stop execution if input isn't string
if (typeof input !== 'string') return false;
if (input.length !== 0) {
for (var i = 0; i < input.length; i++) {
if (input[i] !== " ") {
return false;
}
return true;
}
}
return true;
};
validator.isEmpty(null); // returns false
// Main part to get inputs and apply validation
window.onload = function() {
var signUp = document.getElementById("signUp");
var fName = document.getElementById("fName");
var suButton = document.getElementById("subMit");
// Submit button on the function
suButton.addEventListener('click', function(event) {
isNameValid(fName);
});
signUp.addEventListener('submit', function(event) {
event.preventDefault();
});
function isNameValid(char) {
var val = char.value;
if (validator.isEmpty(val)) {
if (val.length < 2) {
// Display a message if input length is less than 2
char.setCustomValidity("We expect your input should contain at least 2 characters, darling !");
char.style.borderColor = "red";
}
if(!isNaN(val)) {
char.setCustomValidity("Please, enter only characters");
char.style.borderColor = "red";
}
} else {
char.setCustomValidity("");
char.style.borderColor = "green";
}
}
<form id="signUp">
<input type="text" id="fName" name="firstname" placeholder="First name">
<input type="checkbox" name="result" required autofocus> Agree our conditions
<input type="submit" id='subMit' value="SUBMIT">
</form>
It took me a while but I hope following works for you. Let me know if you need help understanding anything. I felt your code was a bit complex so I simplified it.
<script>
function submitForm(){
var formValid = false;
var msg = "";
var fNameElement = document.getElementById("fName");
if(fNameElement){
var fNameValue = fNameElement.value;
if(fNameValue.length < 2){
msg = "We expect your input should contain at least 2 characters, darling !";
}
else if(!(/^[a-zA-Z]+$/.test(fNameValue))){
msg = "Please, enter only characters";
}
else{
formValid = true;
}
if(formValid){
fNameElement.style.borderColor="green";
//do something
}
else{
fNameElement.style.borderColor="red";
alert(msg); // or show it in a div
}
}
}
</script>
<form id="signUp" action="javascript:submitForm()">
<input type="text" id="fName" name="firstname" placeholder="First name">
<input type="checkbox" name="result" required autofocus> Agree our conditions
<input type="submit" id='subMit' value="SUBMIT">
</form>
Fiddle: https://jsfiddle.net/fxumcL3d/3/
trying to learn how to validate form input.
The inputs need to:
1 - Not be empty.
2 - Only contain alphabetic characters (no digits).
When I test (I've only focused on first name input field for now) it will give the correct error message if I leave it blank. But, if I but digits in the field it will submit instead of displaying error message.
What am I doing wrong?
HTML:
<form id="frm1">
<fieldset id="controls">
<div>
<label for="firstname">First Name: </label>
<input type="text" id="firstname">
<span id="errFname" class="errmsg">* You must enter a first name</span>
</div>
<div>
<label for="lastname">Last Name: </label>
<input type="text" id="lastname">
</div>
<div>
<input type="submit" value="Submit">
</div>
</fieldset>
</form>
SCRIPT:
function checkForm(){
document.getElementById("frm1").onsubmit=function() {
//Validate first name: Required, Alphabetic (no numbers)
if(document.getElementById("firstname").value === "") {
document.getElementById("errFname").style.display = "inline";
document.getElementById("firstname").focus();
return false;
} else {
return true;
}//close if
var alphaRegEx = /[a-zA-Z]/;
var alphafname = document.getElementById("firstname").value;
//check if first name has any digits
if (!alphaRegEx.test(alphafname)){
document.getElementById("errFname").style.display = "inline";
document.getElementById("firstname").value="";
document.getElementById("firstname").focus();
return false;
} else {
return true;
}//close if
}//close function
return false;
}//close function (checkForm)
window.onload=checkForm;
The problem is that you are returning inside each if block and that is making the whole submit callback to return.
You should create a variable and return only at the end. Something like this:
function checkForm(){
document.getElementById("frm1").addEventListener("submit", function(e) {
var errors = [];
//Validate first name: Required, Alphabetic (no numbers)
if(document.getElementById("firstname").value === "") {
document.getElementById("errFname").style.display = "inline";
document.getElementById("firstname").focus();
errors.push("required");
}
var alphaRegEx = /[a-zA-Z]/;
var alphafname = document.getElementById("firstname").value;
//check if first name has any digits
if (!alphaRegEx.test(alphafname) && errors.length === 0){
document.getElementById("errFname").style.display = "inline";
document.getElementById("firstname").value="";
document.getElementById("firstname").focus();
errors.push("numeric");
}
//If you want, you can do something with your errors, if not, just return
//You should rethink about handling all errors here showing/hiding messages, etc.
if (errors.length > 0) {
e.preventDefault();
return false;
}
return true;
});//close function
}//close function (checkForm)
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;
}