i am trying to learn html and javascript. I have created an html form and am using javascript to validate the fields. I have a isNaN check for the age field, a regex check for emial and a presence check for all fields. I am currently outputting the form to the address bar but this does not work as i am getting errors.
<title> </title>
<script type="text/javascript">
function validate()
{
var errors = 0;
if (isNumeric(document.getElementById("age").value) == false)
{
errors++;
}
if (emailCheck(document.getElementById("email").value) == false)
{
errors++;
}
var inputBoxes = document.getElementsByTagName('input');
for(var i= 0; i < inputBoxes.length; i++)
{
if(inputBoxes[i].type != 'text') continue;
if(presenceCheck(inputBoxes[i].value) == false)
{
errors++;
}
}
console.log(errors);
if(errors == 0)
{
window.location.assign("output.html#" + "%%" + "name" + "%%" +
document.getElementById("name").value + "%%" + "email" + "%%" +
document.getElementById("email").value + "%%" + "age" + "%%" +
document.getElementById("age").value + "%%" + "comments" + "%%" +
document.getElementById("comments").value);
}
}
function isNumeric(number)
{
return !isNaN(number) && number != null && number != "";
}
function emailCheck(email)
{
var emailRegex = /\s+#\s+.\s+/;
return emailRegex.test(email);
}
function presenceCheck(data)
{
var regex = /\s+/;
return regex.test(data);
}
</script>
Below is the form which is just incased in body tags at the moment
<form id="frmA" name="frmA">
<label name="frmName">Name:</label><br />
<input form="frmA" type="text" name="frmName" id="name"/><br />
<label name="frmEmail">E-Mail:</label><br />
<input form="frmA" type="text" name="frmEmail" id="email"/><br />
<label name="age">Age:</label><br />
<input form="frmA" name="frmAge" id="age"/><br />
<label name="frmComments">Comments:</label><br />
<textarea form="frmA" cols="50" rows="10" id="comments"></textarea><br />
</form>
<button onClick="validate();">Submit</button>
i know that the checks work when no data is present however when i input data in the form and hit submit i am still faced with 4 errors. (there are 5 errors with no data: 3x presence checks, 1 for the regex and one for the isNaN)
My question therefore is why am i still getting errors and why do i get no output.
Any help would be greatly appreciated.
Extra: i would also like the input fields to change colour when there is an error.
Your regexes are wrong. You have /\s+#\s+.\s+/ and it should be /\w+#\w+\.\w+/. You didn't escape the dot and \s matches whitespace, not strings. \w matches word. For a proper email regex you would need much more than that but for your simple case to work this will suffice. The second regex should be /\w+/.
Related
I am trying to make a simple string manipulation program, but I am running into problems.
WHAT THE PROGRAM SHOULD DO:
enteredname field must have at least one space but not in the first position.
enteredname field must contain 'miller' in anycase somewhere.
State field must be only two characters long.
Zip field must start with '45'
Lastly, streetaddress field is not required to contain the word street, but if it does, it is to be changed to 'Street'.
NOT WORKING:
Currently, everything works except the 'street' name check.
ERROR LOCATION:
if (streetaddress.toLowerCase().indexOf("street") == -1)
Current code:
//need to initialize to empty strings
var enteredname = "";
var streetaddress = "";
var city = "";
var state = "";
var zip = "";
function ValidateandDisplay() {
enteredname = document.getElementById("NameTextBox").value;
streetaddress = document.getElementById("StreetAddressTextBox").value;
city = document.getElementById("CityTextBox").value;
state = document.getElementById("StateTextBox").value;
zip = document.getElementById("ZipTextBox").value;
var isValid = CheckEntries(); // call isValid function here that will
// perform all validation and return with a true or false from CheckEntries
if (isValid) {
//string to display
var correctentries = enteredname + "<br/>" +
streetaddress + "<br/>" + city + ", " + state + " " + zip;
document.getElementById("AddressDiv").innerHTML = correctentries;
}
}
function CheckEntries() {
//perform all checks here
//use separate ifs to determine each validation requirement
// alerting the user to the particular problem if something didn't
// pass validation and returning with a false
// ALL of your validation MUST be above the return true statement below
// it will only get to THIS return if all validation (conditions) were ok
if (enteredname[0] == ' ')
{
alert("First position in name field can not be a space.")
return false;
}
if (enteredname.indexOf(" ") == -1)
{
alert("no spaces found in entry.")
return false;
}
if (enteredname.toLowerCase().indexOf("miller") == -1)
{
alert("miller is not in name field.")
return false;
}
if (state.length != 2)
{
alert("State field must be only two characters long.")
return false;
}
if (zip[0] != '4' || zip[1] != '5')
{
alert("Zip field must start with 45.")
return false;
}
if (streetaddress.toLowerCase().indexOf("street") == -1)
{
streetaddress.replace("street", "Street");
return true;
}
else
return true;
}
Name: <input id="NameTextBox" type="text" /> FirstName LastName with a space between<br /> Street Address: <input id="StreetAddressTextBox" type="text" /> <br /> City: <input id="CityTextBox" type="text" /> <br /> State: <input id="StateTextBox" type="text"
/> <br /> Zip: <input id="ZipTextBox" type="text" /> <br />
<input id="Button1" type="button" value="Validate Entries" onclick="ValidateandDisplay()" />
<div id="AddressDiv">If entered correctly, your address will display here.</div>
<input id="Button1" type="button" value="Split a String" onclick="SplitThis()" />
String (array) indices start at 0
state.length > 2 ==> shoulf be "not equal"
(zip[-1] != '4' && zip[0] != '5') => It must be OR. And the indices are wrong
You are missing quotes in last if statement
The contact name input area cannot be left empty and can only have characters and spaces. I'm not that familiar with regex and my online research so far hasn't come up with a simplified explanation on how to do this.
The Regex string I have come across so far is: ^\p{L}+(?: \p{L}+)*$
But I'm not advanced enough to know how to write this as script? Can anyone help.
Thanks.
var contact_name = document.getElementById('contact');
function validate() {
if (contact_name == "") {
alert("Name name must be filled out");
return false;
}
*Do I need a new function, or can I insert script here?
<p>Contact Person: <input id="contact" name="contact" type="text" placeholder="Type Full Name here"></p>
First of all, I'm not sure in your regex, so I googled a little and found this one, which looks good: /^[a-zA-Z\s]*$/. The first issue is where you're trying to compare contact_name == "": contact_name is an element, not input's value, so it should be contact_name.value === "" instead (and I recommend to use strict equality === here). And finally you can check input's value validity via regex using regex.test(contact_name.value), which returns boolean. The solution is rather simple, but if anything isn't clear - feel free to ask.
var contact_name = document.getElementById('contact');
var regex = /^[a-zA-Z\s]*$/;
function validate() {
var isValid = true;
if (contact_name.value === "" || !regex.test(contact_name.value)) {
isValid = false;
}
alert("Is valid: " + isValid)
}
<p>Contact Person: <input id="contact" name="contact" type="text" placeholder="Type Full Name here"></p>
<button onclick="validate()">validate</button>
var contact_name = document.getElementById('contact');
var regex = /^[a-zA-Z\s]*$/;
function validate() {
var isValid = true;
if (contact_name.value === "" || !regex.test(contact_name.value)) {
isValid = false;
}
alert("Is valid: " + isValid)
}
I really don't know how to do this. So I need a JavaScript script that'd look at the contact form field (question name) and make sure it has more than one word before submitting it.
<input type="text" name="question[name]" id="question_name">
I really searched a lot, found some solutions but non of them really worked.
Can you help me?
Here a fiddle http://jsfiddle.net/6q8jJ/4/
html
<input type="text" name="question[name]" id="question_name">
<button onclick="validate();">send</button>
js
function validate(){
var error = 0,
el = document.getElementById("question_name");
if(el.value.replace(/\s+/g, '').length <= 1){ //get value, remove all whitespace, get length
error++;
}
/*
* etc
* your other validation
*/
if(error > 0) {
alert('mhh...');
}else{
alert('ok send for real');
}
}
<input type="text" name="question[name]" id="question_name" onblur="this.value.split(' ').length < 2 ? alert('you need more words here') : '';" />
jsfiddle
Edit to improve it:
HTML code:
<p>
<input type="text" name="question[name]" id="question_name" onblur="CheckErrors.Name(this);" />
<span class="error"></span>
</p>
JS code:
var CheckErrors = {
Config: {
Error_Strings: {
Name: 'you need more words here',
Email: 'the email looks invalid'
//, ....
}
},
Name: function(element){
try{
var error_target = element.nextElementSibling;
if( element.value.split(' ').length < 2 ){
error_target.textContent = this.Config.Error_Strings.Name;
}
else{
error_target.textContent = '';
}
}
catch(e){
console.log(e.stack);
}
}
//, Email: function(element){}....
};
Is there a way to make it so that in an html form, someone types something, and it automatically makes it a capitol letter, like in a software key code input, I would like there to automatically be a dash inserted after every five characters, but not after the last one, meaning that when someone types:
xxxxxxxxxxxxxxxxxxxx
it will automatically be entered in to the form in real time as:
XXXXX-XXXXX-XXXXX-XXXXX
Is there a way to achieve this in real time? Here is my current code for the form:
<form name="key" autocomplete="off">
Key: <input type="text" name="key" maxlength="23"/>
<input type="submit" onclick="check(this.form)" value=" Submit "/>
</form>
<script language="javascript">
function check(form)
{
if (form.key.value == "XXXXX-XXXXX-XXXXX-XXXXX")
{
window.open('URL')
}
else
{
alert ("Invalid Key")
}
}
</script>
This is not optimal at all, but it works !
<script language="javascript">
$(function(){
var isCorrect = false;
$('#key_id').on('keyup',function() {
$(this).val(function(i, text) {
text = text.toUpperCase();
if (text.length < 5) {
isCorrect = false;
return text;
} else if (text.length >= 5 && text.length < 11 && (text.split("-").length - 1) < 1) {
isCorrect = false;
return text.substr(0,5) + '-' + text.substr(5,5);
} else if (text.length >= 11 && text.length < 17 && (text.split("-").length - 1) < 2) {
isCorrect = false;
text = text.replace(/-/g, '');
return text.substr(0,5) + '-' + text.substr(5,5) + '-' + text.substr(10,5);
} else if (text.length >= 17 && text.length < 23 && (text.split("-").length - 1) < 3) {
isCorrect = false;
text = text.replace(/-/g, '');
return text.substr(0,5) + '-' + text.substr(5,5) + '-' + text.substr(10,5) + '-' + text.substr(15,5);
} else if (text.length >= 23) {
isCorrect = true;
text = text.replace(/-/g, '');
return text.substr(0,5) + '-' + text.substr(5,5) + '-' + text.substr(10,5) + '-' + text.substr(15,5);
} else {
isCorrect = false;
return text;
}
});
});
$("#my_form").submit(function(){
if(isCorrect) {
window.open('URL');
} else {
alert('invalid');
}
});
});
</script>
On the event keyup (releasing a key = letter/number), I do :
UpperCase
Return the text normally if less than 5 char
Return the text with '-' if more than 5 char but less than 10+1 char (the +1 is because we added '-'). Else return the text normally if already added the '-'
Return the text with 2 '-' if more than 10+1 char but less than 15+2 char (because 2 '-'). Else return the text normally if already added the 2 '-'.
And so on...
EDIT :
Updated code, you will need to use jQuery and put an id to your input id="key_id"
EDIT :
New code, easier for you to use it. Still needs jQuery (you can do it without, search on StackOverflow how to convert $(id).val() in pure javascript).
http://jsfiddle.net/f8BzW/1/
You could use css for the capitalization: text-transform: uppercase;
And with jquery + this plugin: http://digitalbush.com/projects/masked-input-plugin/
jQuery(function($){
$("#key").mask("xxxxx-xxxxx-xxxxx-xxxxx-xxxxx");
});
check out the demo
So after reading the comments I decided to code it all out in a demo for you.
Here is the fiddle: http://jsfiddle.net/doppel/v3eLX/#&togetherjs=KgqxizB1Fc
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="./css/style.css">
<title></title>
</head>
<body>
<form name="key" autocomplete="off">
<label for="key">Key:</label><input type="text" name="key" id="key" style="text-transform:uppercase;" maxlength="23"/>
<input type="submit" onclick="check(this.form)" id="btn" value="Submit"/>
</form>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="jquery.maskedinput.js"></script>
<script language="javascript">
function check(form)
{
if (form.key.value == "XXXXX-XXXXX-XXXXX-XXXXX")
window.open('URL')
else
alert ("Invalid Key")
}
$("document").ready(function() {
$("#key").mask("aaaaa-aaaaa-aaaaa-aaaaa",{placeholder:" "});
});
</script>
</body>
Note you will have to download the plugin and include it like I have or copy the fiddle code.
So as you see I added a label because its proper,
I added an Id to the input to make it easier to select, Note I also added an in-line style to force Uppercase as stated above ^^^^.
Now the script $("document").ready(function() {gets jquery ready to be used.
$("#key").mask("aaaaa-aaaaa-aaaaa-aaaaa",{placeholder:" "}); This statement selects id key as the target of the function Mask which is the plugin to be called stating that we want a format aaaaa-aaaaa-aaaaa-aaaaa where a is equal to "letter". Note only "a" and "9" denote alpha and numeric data. And "{placeholder:" "})" the plugin by default puts underscores as placeholders but I changed it to a space to look more what you want I think.
How do I validate dd/mm/yyyy, numeric loan amount, alphabetic first, last name together. I am having trouble using this forum. Thanks for responding so fast!
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
<!--//
function validate(form){
var message = 'Please fill in the following fields:\n\n\t';
for(var i=0; i<form.elements.length; i++){
if(form.elements[i].value.length == 0){
message+= form.elements[i].name.toUpperCase()+'\n\t';
}
}
message+= '\nOK submit incomplete form';
message+= '\nCANCEL return to the form';
message = confirm(message);
if(!message){ return false };
else{ return true };
}
//-->
</script>
</head>
<body>
<form name="loanform" action="processform.htm" method="get" onsubmit="return validate(this)">
First Name: <input type="text" name="firstname" maxlength="15"><br>
Last Name: <input type="text" name="lastname" maxlength="15"><br>
Birth Date: <input type="text" name="birthdate" maxlength="8"><br>
Loan Amount: <input type="text" name="loanamount" maxlength="6" ><br>
Years: <input type="text" name="years" maxlength="2"><br>
<br>
<input type="reset" value="clear">
<input type="submit" value="submit">
</form>
</body>
</html>
You can use a function like this. It sets up a regular expression for each type of field and then makes a table that says which regular expression to use for which form element. It uses the named form elements to access the individual values.
function validate(form) {
var nameRE = /^[A-Za-z \.]+$/;
var dateRE = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var amountRE = /^\$?[\d\.,]+$/;
var yearsRE = /^\d+$/;
var formItems = [
{name: "firstname", re: nameRE, tag: "First Name"},
{name: "lastname", re: nameRE, tag: "Last Name"},
{name: "birthdate", re: dateRE, tag: "Birth Date", isDate: true},
{name: "loanamount", re: amountRE, tag: "Loan Amount", min: 50000, max: 750000},
{name: "years", re: yearsRE, tag: "Years", min: 5, max: 30}
];
var item, val, num, month, day, year, valid, matches, incomplete = false;
var msg = 'Please fill in the following fields:\n\n\t';
for (var i = 0; i < formItems.length; i++) {
item = formItems[i];
// strip leading or trailing whitespace
var val = form[item.name].value.replace(/^\s+|\s+$/g, "");
form[item.name].value = val;
// see if it matches the regex
valid = item.re.test(val);
if (valid && item.isDate) {
matches = val.match(item.re);
month = parseInt(matches[1], 10);
day = parseInt(matches[2], 10);
year = parseInt(matches[3], 10);
if (month <= 0 || month > 12 ||
day <= 0 || day >= 31 ||
year < 1900 || year > 2020) {
valid = false;
}
}
if (!valid) {
incomplete = true;
msg += item.tag + '\n\t';
} else {
if (item.min && item.max) {
// clear out non-numeric chars
val = val.replace(/[,\$\s]/g, "");
// convert to a number
num = parseInt(val, 10);
// compare to min and max
if (num < item.min || num > item.max) {
incomplete = true;
msg += item.tag + " (must be between " + item.min + " and " + item.max + ")\n\t";
}
}
}
}
if (incomplete) {
msg += '\nOK submit incomplete form';
msg += '\nCANCEL return to the form';
return(confirm(msg));
}
return(true);
}
Working demo here: http://jsfiddle.net/jfriend00/GChEP/
A way to do would be to use classes to know what kind of validation you need for a given input. Also, you can use the title attribute to have a more human-friendly representiation of the input.
Your HTML would then look like:
<form name="loanform" action="processform.htm" method="get" onsubmit="return validate(this)">
First Name (text only): <input class="validate-text" title="First Name" type="text" name="firstname" maxlength="15"><br>
Last Name (text only): <input class="validate-text" title="Last Name" type="text" name="lastname" maxlength="15"><br>
Birth Date (format dd/mm/yyyy): <input class="validate-date" title="Birth Date" type="text" name="birthdate" maxlength="8"><br>
Loan Amount (US dollars, numeric only): <input class="validate-number" title="Loan Amount" type="text" name="loanamount" maxlength="6" ><br>
Years (numeric only): <input class="validate-number" title="Years" type="text" name="years" maxlength="2"><br>
<br>
<input type="reset" value="clear">
<input type="submit" value="submit">
</form>
And your JavaScript function (regular expressions seem to be the best way to go):
function validate(f) {
var message=new Array(); //will contain the fields that are misfilled
var reText=new RegExp("^[a-z \-'\.]+$", "i"); //a RegExp to match names: only letters, "-", "'" and "." allowed
var reDate=new RegExp("^[0-9]{2}/[0-9]{2}/[0-9]{4}$"); //a RegExp to match a date in the format dd/mm/yyyy
var reNumber=new RegExp("^[0-9]+$"); //a RegExp to match a number
for(var e in f.elements) { //loop on every input of the form
var test=null; //set or reset the RegExp to use for the current input
var input=f.elements[e]; //assign the input to a var (easier to type, not needed)
if(!input.className) //if this input doesn't have any class declared
continue; //then we skip the rest of the loop to keep going with the next input
var classes=input.className.split(" "); //maybe the input has several classes, so we split them in a "classes" array
for(var c in classes) { //we loop on every class of the current input
switch(classes[c]) { //and we test if the current class of the current input is one of the classes we're interested in
case "validate-text": //if it is a text
test=reText; //the variable "test" will contain the RegExp we want to use
break;
case "validate-date": //same for a date
test=reDate;
break;
case "validate-number": //and same for a number
test=reNumber;
break;
default: //if the class is not something we want, nothing to do
break;
} //end switch
} //end classes loop
//here test is either null (no "validate-something" class found for the current input), or it contains the RegExp telling us the kind of input we must validate.
if(test!=null && !input.value.match(test)) { //if it is not null and if the input's value does not match the RegExp
message.push(input.title); //we add the field to the "message" array
}
} //end input loop
if(message.length>0) { //if the arary is not empty, we display a confirm box
return confirm("Please correctly fill the following field(s), or click OK to send an incomplete form:\n"+message.join("\n"));
}
//otherwise, the form is correctly filled, we return true to submit the form
return true;
}