My validating a captcha using JavaScript is not working - javascript

<script>
function validate2(id)
{
var regex = [a-z];
var ctrl = document.getElemetnById(id);
if (regex.test(ctrl.value)) {
return true;
}
else {
return false;
}
}
</script>
<script>
function TestCompanyName(txtCompanyName){
var obj = document.getElementById(txtCompanyName);
var RegEx = /THE DAMN REGULAR EXPRESSION/
if(RegEx.test(obj.value)==false)
{
alert("Invalid");
}
}
</script>
</script>
<script>
function checklname(input1)
{
var pattern=/^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
return pattern.test(input1);
}
if(!isvalid) {
alert('Invalid name');
document.getElementById("input1").value = "";
}
}
</script>
<script>
function phonenumber(telno) {
var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
if(telno.value.match(phoneno))
{
return true;
}
else {
alert("message");
return false;
}
}
</script>
<script>
function phonenumber2(mobileno) {
var phoneno1 = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
if(mobileno.value.match(phoneno1))
{
return true;
}
else {
alert("message");
return false;
}
}
</script>
<script>
function validate() {
var ta = document.getElementById("ta").value;
var answer = document.getElementbyId("answer").value;
var digit1 = parseInt(document.getElementById("digit1").innerHTML);
var digit2 = parseInt(document.getElementById("digit2").innerHTML);
var sum = digit1 + digit2;
if(answer == null || answer == ""){
alert("please add the number");
return false;
}else if(answer != sum){
alert("you math is wrong");
}else if(ta == null || ta == ""){
alert("please fill in the textarea");
}else{
document.getElementById("status").innerHTML = "processing";
document.getElementById("answer").innerHTML = "";
}
}
function randomNums(){
var rand_num1 = Math.floor(Math.random() * 10) +1;
var rand_num2 = Math.floor(Math.random() * 10) +1;
document.getElementById("digit1").innerHTML = rand_num1;
document.getElementById("digit2").innerHTML = rand_num2;
}
</script
<script>
function checkEmail(inputvalue){
var pattern=/^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
return pattern.test(inputvalue);
}
checkEmail('rte#co') // false
checkEmail('rte#co.com') // true
</script>
<script>
var address = /^[a-zA-Z0-9-\/] ?([a-zA-Z0-9-\/]|[a-zA-Z0-9-\/] )*[a-zA-Z0-9-\/]$/;
if ( address.test($.trim($('#address').val())) == false)
{
alert('invalid address ');
}
</script>
<script>
function IsValidZipCode(zipcode) {
var isValid = /[\^$%#!#&\*:<>\?\/\\~\{\}\(\)\+|]/.test(zipcode);
if (!isValid){
alert('Invalid ZipCode');
document.getElementById("zipcode").value = "";
}
</script>
<script type="text/javascript" src="js/bootstrap-3.1.1.min.js"></script>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<?php include("include files/favicon.php"); ?>
</head>
<body itemscope itemtype="http://schema.org/Organization">
<?php
include("include files/header.php");
?>
<?php
include("include files/navigation.php");
?>
<!--breadcrumb-->
<div id='location'>
<div id="BannerAndNavigatorHtmlBlock_StoreNavigator_pnNavigator" itemscope="" itemtype="http://schema.org/BreadcrumbList" class="btn-group btn-breadcrumb">
<span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem" class="btn btn-success">
<a itemprop="item" href="/">
<span class="glyphicon glyphicon-home" itemprop="name">
</span>
</a>
<span itemprop="position" content="1">
</span>
</span>
</span>
<span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"class="btn btn-success">
<span itemprop="name">Playing Card Quote</span><span itemprop="position" content="2"></span>
</span>
</div>
</div>
<!--Main Content-->
<div class="wrapper">
<div class="container">
<div> </div>
<div class="well">
<form action="thank-you.php" method="post" id="form1" onsubmit="MM_validateForm('quantity','','R','fname','','R','email','','NisEmail','telno','','RisNum','address','','R','city','','R','state','','R','country','','R','zipcode','','R');return document.MM_returnValue && jcap();">
<fieldset>
<legend>
<h1>Fill Quote Form</h1>
</legend>
<div class="quote-form">
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6">Plastic Coated Paper :</label>
<div class="col-sm-3">
<select class="form-control" name="plastic_coated_paper" id="plastic_coated_paper" onchange="chgSelect('coatedpaper');">
<option selected value="0" id="selectpaper">Select Paper</option>
<option>Black Centered 330</option>
<option>Black Centered 320</option>
<option>Black Centered 315</option>
<option>Black Centered 305</option>
<option>Black Centered 300</option>
<option>Black Centered 280</option>
<option>White Centered 330</option>
<option>White Centered 320</option>
<option>White Centered 315</option>
<option>White Centered 305</option>
<option>White Centered 300</option>
<option>White Centered 280</option>
</select>
</div>
<div class="col-sm-3" style="text-align:center;">
</div>
<br>
<br>
<center>OR</center>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6">100% Pure Plastic : </label>
<h2>Your Contact Information :</h2>
<form action="" method="POST">
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> First Name</label>
<div class="col-sm-3">
<div>
<input name="fname" id= "id" type="text" onSubmit="" tabindex="2" required="required">
</div>
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Last Name</label>
<div class="col-sm-3">
<div>
<label>
<input name="lname" id="input1" type="text" tabindex="2" required="required">
</label>
</div>
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Email Id</label>
<div class="col-sm-3">
<div>
<label>
<input name="email" type="email" tabindex="2" required="required">
</label>
</div>
</div>
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<div class="col-sm-6">
</div>
<div class="col-sm-5">(Please type in a correct email address , as the quotes will be forwarded there)</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Telephone Number</label>
<div class="col-sm-3">
<div>
<label>
<input name="telno" id="telno" type="text" tabindex="2" required="required">
</label>
</div>
</div>
<div class="col-sm-3">( Do not enter space)
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Mobile Number</label>
<div class="col-sm-3">
<div>
<label>
<input name="mobileno" id="mobileno" type="text" tabindex="2" required="required">
</label>
</div>
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"> <i>*</i> Company Name</label>
<div class="col-sm-3">
<div>
<label>
<input type="text" name="txtCompanyName" id="txtCompanyName" required="required" onclick="TestCompanyName('txtCompanyName')">
</label>
</div>
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Address</label>
<div class="col-sm-3">
<input id="address" class="address" type="text" name="address"
onchange="IsValidAddress(this.form.address.value)" required="required" >
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Zip Code :</label>
<div class="col-sm-3">
<input id="zipcode" class="zipcode" type="text" name="zipcode" onchange="IsValidZipCode(this.form.zipcode.value)" required="required" >
<br />
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> City</label>
<div class="col-sm-3">
<input class="form-control" name="city" type="text" id="city" required="required" value="">
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> State</label>
<div class="col-sm-3">
<input class="form-control" name="state" type="text" id="state" value="" required ="required">
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Country</label>
<div class="col-sm-3">
<input class="form-control" name="country" type="text" id="country" value="" required="required">
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"> Fax</label>
<div class="col-sm-3">
<input class="form-control" name="fax" type="text" id="fax" value="" required ="required">
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Captcha</label>
<div class="col-sm-2">
</div>
<div class="col-sm-3">
<body>
<form name="review" ACTION="newpg.html" METHOD="POST" onsubmit="return checkform(this);">
<font color="#DD0000">Enter Code ></font> <span id="txtCaptchaDiv" style="background-color:#A51D22;color:#FFF;padding:5px"></span>
<input type="hidden" id="txtCaptcha" />
<input type="text" name="txtInput" id="txtInput" size="15" />
<input type="submit" value="Submit"/>
</form>
<script type="text/javascript">
function checkform(theform){
var why = "";
if(theform.txtInput.value == ""){
why += "- Security code should not be empty.\n";
}
if(theform.txtInput.value != ""){
if(ValidCaptcha(theform.txtInput.value) == false){
why += "- Security code did not match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
//Generates the captcha function
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("txtCaptchaDiv").innerHTML = code;
// Validate the Entered input aganist the generated security code function
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
if (str1 == str2){
return true;
}else{
return false;
}
}
// Remove the spaces from the entered and generated code
function removeSpaces(string){
return string.split(' ').join('');
}
</script>
</body>
<div class="col-sm-3">
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<div class="col-sm-12">
<center>
<input type="submit" value="Submit" class="btn1" name="submit" id="send">
</center>
</div>
</div>
</div>
<div> </div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<!---footer---><?php include("include files/footer.php");?>
</body>
</html>
I am not able to provide validation for captcha using validation? My function is not displaying message for me if security code did not match or security code should not be empty.
What is the problem in the program? Why is not validating my captcha properly? I tried it many times but not able to validate my captcha code
What is the error in the page for captcha validation? What is the correct validation for captcha ?

The code you posted does not have any issues. It does what it is supposed to do, generate a code and validate that the input matches it before allowing the form to be submitted.
However, if you are really interested in preventing bots from submitting the form, then this code is not going to help you at all. You generate the code on the client and save it in your input. A bot would read that input and provide the captcha with no issues at all.
EDIT: suggestion for recaptcha
I would suggest that you integrate your application with an established recaptcha provider, as is for example recaptcha. Please note that the validation of the captcha input should be performed in your server
You can find further details for recaptcha here.

The code is working as you might expect. Please review the fiddle I had to made no change at all.
https://jsfiddle.net/43m63ezf/
HTML
<label>Captcha</label>
<form name="review" ACTION="palying-cards-quote.php" METHOD="POST" onsubmit="return checkform(this);">
<font color="#DD0000">Enter Code </font> <span id="txtCaptchaDiv" style="background-color:#A51D22;color:#FFF;padding:5px"></span>
<input type="hidden" id="txtCaptcha" />
<input type="text" name="txtInput" id="txtInput" size="15" />
<input type="submit" value="Submit" />
</form>
JS
function checkform(theform) {
var why = "";
if (theform.txtInput.value == "") {
why += "- Security code should not be empty.\n";
}
if (theform.txtInput.value != "") {
if (ValidCaptcha(theform.txtInput.value) == false) {
why += "- Security code did not match.\n";
}
}
if (why != "") {
alert(why);
return false;
}
}
//Generates the captcha function
var a = Math.ceil(Math.random() * 9) + '';
var b = Math.ceil(Math.random() * 9) + '';
var c = Math.ceil(Math.random() * 9) + '';
var d = Math.ceil(Math.random() * 9) + '';
var e = Math.ceil(Math.random() * 9) + '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("txtCaptchaDiv").innerHTML = code;
// Validate the Entered input aganist the generated security code function
function ValidCaptcha() {
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
if (str1 == str2) {
return true;
} else {
return false;
}
}
// Remove the spaces from the entered and generated code
function removeSpaces(string) {
return string.split(' ').join('');
}

Related

How to clear javascript validation error messages with the reset button

I have a simple form page, where there are several form validations. So far, the RESET button only clears the text field values.
But I need the validation messages to clear when the RESET button is pressed.
So far I have seen jQuery methods, but have no idea of implementing it as I am still learning.. Are there any other methods to do this without jQuery..?
Any help would be highly appreciated.
Here's my code...
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="author" content="Koshila">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Contact|Frittery</title>
<link rel="stylesheet" href="about.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css" integrity="sha384-VCmXjywReHh4PwowAiWNagnWcLhlEJLA5buUprzK8rxFgeH0kww/aWY76TfkUoSX" crossorigin="anonymous">
<script>
function validation() {
var formFname = document.getElementById("fname").value;
var formLname = document.getElementById("lname").value;
var formEmail = document.getElementById("email").value;
var formNumber = document.getElementById("pnumber").value;
//Validate first name
if (formFname.length == 0) {
document.getElementById("fnameMessage").innerHTML = "<em>You did not enter your first name</em>"
}
//Validate last name
if (formLname.length == 0) {
document.getElementById("lnameMessage").innerHTML = "<em>You did not enter your last name</em>"
}
//Validate email
if (formEmail.length == 0) {
document.getElementById("emailMessage").innerHTML = "<em>You did not enter your email</em>"
} else {
var regex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (regex.test(formEmail) === false) {
document.getElementById("emailMessage").innerHTML = "<em>Please enter a valid email</em>"
}
}
//Validate phone
if (formNumber.length == 0) {
document.getElementById("phoneMessage").innerHTML = "<em>You did not enter your phone number</em>"
} else if (formNumber.length != 10) {
document.getElementById("phoneMessage").innerHTML = "<em>Phone Number must be exactly 10 digits</em>"
return false;
} else
return true;
}
</script>
</head>
<body>
<div class="container">
<h2>General Enquiry Form</h2>
<form method="POST" action="#" onsubmit="validation(); return false;">
<div class="form-group row">
<label class="col-form-label col-sm-2" for="fname">First Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="fname" name="fname">
</div>
<div class="col-sm-4">
<span id="fnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="lname">Last Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="lname" name="lname">
</div>
<div class="col-sm-4">
<span id="lnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="email">Email</label>
<div class="col-sm-6">
<input class="form-control" type="email" id="email" name="email">
</div>
<div class="col-sm-4">
<span id="emailMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="pnumber">Phone</label>
<div class="col-sm-6">
<input class="form-control" type="tel" id="pnumber" name="pnumber">
</div>
<div class="col-sm-4">
<span id="phoneMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="message">Message</label>
<div class="col-sm-10">
<textarea class="form-control" id="message" name="message" style="height: 200px;"></textarea>
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 ">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-secondary">Reset</button>
</div>
</div>
</form>
</div>
<hr>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/js/bootstrap.min.js" integrity="sha384-XEerZL0cuoUbHE4nZReLT7nx9gQrQreJekYhJD9WNWhH8nEW+0c5qq7aIo2Wl30J" crossorigin="anonymous"></script>
</body>
</html>
Don't reset them manual by repeating code. Define a custom reset function which iterates over error messages and empty all of them:
function resetForm() {
var elems = document.querySelectorAll(".text-danger");
elems.forEach(itm => {
document.getElementById(itm.id).innerHTML = ''
})
}
Also don't put any script tag in your head tag. Read more here
Full code:
function resetForm() {
var elems = document.querySelectorAll(".text-danger");
elems.forEach(itm => {
document.getElementById(itm.id).innerHTML = ''
})
}
function validation() {
var formFname = document.getElementById("fname").value;
var formLname = document.getElementById("lname").value;
var formEmail = document.getElementById("email").value;
var formNumber = document.getElementById("pnumber").value;
//Validate first name
if (formFname.length == 0) {
document.getElementById("fnameMessage").innerHTML = "<em>You did not enter your first name</em>"
}
//Validate last name
if (formLname.length == 0) {
document.getElementById("lnameMessage").innerHTML = "<em>You did not enter your last name</em>"
}
//Validate email
if (formEmail.length == 0) {
document.getElementById("emailMessage").innerHTML = "<em>You did not enter your email</em>"
} else {
var regex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (regex.test(formEmail) === false) {
document.getElementById("emailMessage").innerHTML = "<em>Please enter a valid email</em>"
}
}
//Validate phone
if (formNumber.length == 0) {
document.getElementById("phoneMessage").innerHTML = "<em>You did not enter your phone number</em>"
} else if (formNumber.length != 10) {
document.getElementById("phoneMessage").innerHTML = "<em>Phone Number must be exactly 10 digits</em>"
return false;
} else
return true;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="author" content="Koshila">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Contact|Frittery</title>
<link rel="stylesheet" href="about.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css" integrity="sha384-VCmXjywReHh4PwowAiWNagnWcLhlEJLA5buUprzK8rxFgeH0kww/aWY76TfkUoSX" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2>General Enquiry Form</h2>
<form method="POST" action="#">
<div class="form-group row">
<label class="col-form-label col-sm-2" for="fname">First Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="fname" name="fname">
</div>
<div class="col-sm-4">
<span id="fnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="lname">Last Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="lname" name="lname">
</div>
<div class="col-sm-4">
<span id="lnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="email">Email</label>
<div class="col-sm-6">
<input class="form-control" type="email" id="email" name="email">
</div>
<div class="col-sm-4">
<span id="emailMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="pnumber">Phone</label>
<div class="col-sm-6">
<input class="form-control" type="tel" id="pnumber" name="pnumber">
</div>
<div class="col-sm-4">
<span id="phoneMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="message">Message</label>
<div class="col-sm-10">
<textarea class="form-control" id="message" name="message" style="height: 200px;"></textarea>
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 ">
<button onclick="validation(); return false;" class="btn btn-primary">Submit</button>
<button class="btn btn-secondary" onclick="resetForm(); return false;">Reset</button>
</div>
</div>
</form>
</div>
<hr>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/js/bootstrap.min.js" integrity="sha384-XEerZL0cuoUbHE4nZReLT7nx9gQrQreJekYhJD9WNWhH8nEW+0c5qq7aIo2Wl30J" crossorigin="anonymous"></script>
</body>
<button type="reset" class="btn btn-secondary" onclick="clearErrors();">Reset</button>
function clearErrors() {
document.getElementById("emailMessage").innerHTML = "";
// ... repeat for other messages
}
You need to call the eraseText function separately like mentioned below
function eraseText() {
document.getElementById("fnameMessage").innerHTML = "";
document.getElementById("lnameMessage").innerHTML = "";
document.getElementById("emailMessage").innerHTML = "";
document.getElementById("phoneMessage").innerHTML = "";
}
<button onClick="eraseText()" type="reset" class="btn btn- secondary">Reset</button>
As the error/validation messages are displayed within span elements of the same class text-danger you can easily query the DOM using querySelectorAll to return a nodelist and then iterate through that collection and set the span text content to an empty string.
Note that I added a name to the form and used that name within the anonymous function in the event handler. With a name assigned to the form also means that you can identify elements simply by doing something like this:
const form=document.forms.enquiry;
const formFname=form.fname;
const formLname=form.lname;
etc etc
document.querySelector('button[type="reset"]').addEventListener('click',e=>{
e.preventDefault();
document.querySelectorAll('.text-danger').forEach(span=>span.textContent='')
document.forms.enquiry.reset()
})
function validation()
{
var formFname = document.getElementById("fname").value;
var formLname = document.getElementById("lname").value;
var formEmail = document.getElementById("email").value;
var formNumber = document.getElementById("pnumber").value;
//Validate first name
if(formFname.length ==0)
{
document.getElementById("fnameMessage").innerHTML ="<em>You did not enter your first name</em>"
}
//Validate last name
if(formLname.length ==0)
{
document.getElementById("lnameMessage").innerHTML ="<em>You did not enter your last name</em>"
}
//Validate email
if(formEmail.length ==0)
{
document.getElementById("emailMessage").innerHTML ="<em>You did not enter your email</em>"
}
else
{
var regex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(regex.test(formEmail)===false)
{
document.getElementById("emailMessage").innerHTML ="<em>Please enter a valid email</em>"
}
}
//Validate phone
if(formNumber.length ==0)
{
document.getElementById("phoneMessage").innerHTML ="<em>You did not enter your phone number</em>"
}
else if(formNumber.length !=10)
{
document.getElementById("phoneMessage").innerHTML ="<em>Phone Number must be exactly 10 digits</em>"
return false;
}
else
return true;
}
<div class="container">
<h2>General Enquiry Form</h2>
<form name='enquiry' method="POST" action="#" onsubmit="validation(); return false;">
<div class="form-group row">
<label class="col-form-label col-sm-2" for="fname">First Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="fname" name="fname" >
</div>
<div class="col-sm-4">
<span id="fnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="lname">Last Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="lname" name="lname" >
</div>
<div class="col-sm-4">
<span id="lnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="email">Email</label>
<div class="col-sm-6">
<input class="form-control" type="email" id="email" name="email" >
</div>
<div class="col-sm-4">
<span id="emailMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="pnumber">Phone</label>
<div class="col-sm-6">
<input class="form-control" type="tel" id="pnumber" name="pnumber">
</div>
<div class="col-sm-4">
<span id="phoneMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="message">Message</label>
<div class="col-sm-10">
<textarea class="form-control" id="message" name="message" style="height: 200px;"></textarea>
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 ">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-secondary">Reset</button>
</div>
</div>
</form>
</div>
take a look for my code
html code:
<div class="tech-news__search__container">
<div class="tech-news__search">
<input
id="subscribeInput"
type="text"
class="tech-news__search-input"
placeholder="example#gmail.com"
>
<button class="tech-news__search-button" id="subscribeButton">Subscribe</button>
</div>
<div class="resultBlock">
<p class="listOfSubscribers" id="listOfSubscribers"></p>
<div id="result"></div>
<div id="deleteAll"></div>
</div>
</div>
js code:
let node = null
let deleteAll
function renderItems() {
const items = getItem()
if (items.length) {
const listOfSubscribers = document.getElementById('listOfSubscribers')
listOfSubscribers.innerHTML = 'Subscribers'
items.map(item => {
node = document.createElement("LI");
let textnode = document.createTextNode(item);
node.appendChild(textnode);
document.getElementById("result").appendChild(node);
})
deleteAll = document.getElementById('deleteAll')
deleteAll.innerHTML = 'Delete All'
deleteAll.addEventListener('click', deleteItems)
}
}
renderItems()
function deleteItems() {
sessionStorage.removeItem('subscribers')
window.location.reload()
}

JS validation mistakes

I got a problem with my validation of textboxes.
I am trying to get something like this.
Click on the button, give a message when something is not filled in, while you fill the empty textbox, the 1 message of that textbox should dissapear.
If you click the button again, with 1 empty textbox, only the message of that textbox should appear.
If you click it twice with nothing filled, it should only appear once ...
I messed something up here ...
can someone get me on again?
Thank you in advance!
var list2 = [];
function valideer(el) {
divOutput = document.getElementById("msgbox1");
var strValideer = "<ul>";
if (document.getElementById("naam").value === "") {
list2.push("naam");
} if (document.getElementById("voornaam").value === "") {
list2.push("voornaam");
} if (document.getElementById("straatnr").value === "") {
list2.push("straatnr");
} if (document.getElementById("postgem").selectedIndex === 0) {
list2.push("postgem");
} if (document.getElementById("telgsm").value === "") {
list2.push("telgsm");
} if (document.getElementById("email").value === "") {
list2.push("email");
}
for (var i = 0; i < list2.length; i++) {
strValideer += "<li><b>" + list2[i] + ": </b>verplicht veld</li>";
}
strValideer += "</ul>";
divOutput.innerHTML = strValideer;
}
function inputChange(el) {
divOutput = document.getElementById("msgbox1");
strValideer = "<ul>";
var naam = document.getElementById("naam").value;
if (naam !== "") {
list2.splice(list2.indexOf(el.name), 1);
}
for (var i = 0; i < list2.length; i++) {
strValideer += "<li><b>" + list2[i] + ": </b>verplicht veld</li>";
}
strValideer += "</ul>";
divOutput.innerHTML = strValideer;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="bootstrap/css/bootstrap_custom.min.css" type="text/css" rel="stylesheet" />
<!--lay-out met bootstrap grid-->
<link href="style.css" type="text/css" rel="stylesheet" />
<script src="woodfactory.js" type="text/javascript"></script>
</head>
<body>
<section class="container" id="userform">
<form action="js_form_ontvanger.html" method="get" class="form-horizontal" name="frmUserform" id="frmUserform" onsubmit="return validate(this)" oninput="inputChange(this)">
<fieldset>
<legend>Persoonlijke gegevens</legend>
<div class="container">
<div class="row">
<div class="span7">
<div class="control-group">
<label class="control-label" for="naam">naam:</label>
<div class="controls">
<input type="text" id="naam" name="naam" placeholder="naam" required onsubmit="valideer(this)" onclick="inputChange(this)">
</div>
</div>
<div class="control-group">
<label class="control-label" for="voornaam">voornaam:</label>
<div class="controls">
<input type="text" id="voornaam" name="voornaam" placeholder="voornaam" required onsubmit="valideer(this)" onclick="inputChange(this)">
</div>
</div>
<div class="control-group">
<label class="control-label" for="straatnr">straat+nr:</label>
<div class="controls">
<input type="text" id="straatnr" name="straatnr" placeholder="straat+nr" required onsubmit="valideer(this)" onclick="inputChange(this)">
</div>
</div>
<div class="control-group">
<label class="control-label" for="postgem">post+gem:</label>
<div class="controls">
<select id="postgem" required onsubmit="valideer(this)" onclick="inputChange(this)">
<option value="">-- maak een keuze --</option>
<option value="2000">2000 Antwerpen</option>
<option value="9000">9000 Gent</option>
<option value="9300">9300 Aalst</option>
<option value="9400">9400 Ninove</option>
<option value="9450">9450 Haaltert</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="telgsm">tel/gsm:</label>
<div class="controls">
<input type="text" id="telgsm" name="telgsm" placeholder="tel/gsm" required onsubmit="valideer(this)" onclick="inputChange(this)">
</div>
</div>
<div class="control-group">
<label class="control-label" for="email">email:</label>
<div class="controls">
<input type="email" id="email" name="email" placeholder="e-mail" required onsubmit="valideer(this)" onclick="inputChange(this)">
</div>
</div>
<!--einde span7-->
</div>
<div class="span4 valid">
<div id="msgbox1" class="alert alert-error">
<div class="span1">
</div>
</div>
</div>
<div class="span1">
<div class="span1">
</div>
<!--einde row-->
</div>
<!--einde container-->
</div>
</div>
</fieldset>
<fieldset>
<div class="container">
<div class="row">
<div class="span7">
<div class="control-group">
<div class="controls">
</div>
</div>
<div class="control-group">
<div class="controls">
</div>
</div>
<div class="control-group">
<div class="controls">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success" onclick="valideer(this)">Verzenden</button>
</div>
</div>
<div class="span4 valid">
<div id="msgbox3" class="alert alert-success"></div>
</div>
<div class="span1"><!--lege kolom--></div>
<!--einde row-->
</div>
<!--einde container-->
</div>
</fieldset>
</form>
</section>
<footer class="container">
<p>© 2013 The Wood Factory </p>
</footer>
</body>
</html>
I feel like your approach is a little more complicated than it needs to be.. See my attempt below
function valideer(current) {
var ids = ['naam', 'voornaam', 'straatnr', 'postgem', 'telgsm', 'email'];
var str = '<ul>';
ids.forEach(function(id) {
var el = document.getElementById(id);
if (el.value === '' && el !== current) {
str += "<li><b>" + id + ": </b>verplicht veld</li>";
}
});
str += '</ul>';
var outputDiv = document.getElementById("msgbox1");
outputDiv.innerHTML = str;
}
function handleFormSubmit(ev) {
ev.preventDefault();
valideer();
return false;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="bootstrap/css/bootstrap_custom.min.css" type="text/css" rel="stylesheet" />
<!--lay-out met bootstrap grid-->
<link href="style.css" type="text/css" rel="stylesheet" />
<script src="woodfactory.js" type="text/javascript"></script>
</head>
<body>
<section class="container" id="userform">
<form action="js_form_ontvanger.html" method="get" class="form-horizontal" name="frmUserform" id="frmUserform" onsubmit="handleFormSubmit">
<fieldset>
<legend>Persoonlijke gegevens</legend>
<div class="container">
<div class="row">
<div class="span7">
<div class="control-group">
<label class="control-label" for="naam">naam:</label>
<div class="controls">
<input type="text" id="naam" name="naam" placeholder="naam" required onclick="valideer(this)">
</div>
</div>
<div class="control-group">
<label class="control-label" for="voornaam">voornaam:</label>
<div class="controls">
<input type="text" id="voornaam" name="voornaam" placeholder="voornaam" required onclick="valideer(this)">
</div>
</div>
<div class="control-group">
<label class="control-label" for="straatnr">straat+nr:</label>
<div class="controls">
<input type="text" id="straatnr" name="straatnr" placeholder="straat+nr" required onclick="valideer(this)">
</div>
</div>
<div class="control-group">
<label class="control-label" for="postgem">post+gem:</label>
<div class="controls">
<select id="postgem" required onclick="valideer(this)">
<option value="">-- maak een keuze --</option>
<option value="2000">2000 Antwerpen</option>
<option value="9000">9000 Gent</option>
<option value="9300">9300 Aalst</option>
<option value="9400">9400 Ninove</option>
<option value="9450">9450 Haaltert</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="telgsm">tel/gsm:</label>
<div class="controls">
<input type="text" id="telgsm" name="telgsm" placeholder="tel/gsm" required onclick="valideer(this)">
</div>
</div>
<div class="control-group">
<label class="control-label" for="email">email:</label>
<div class="controls">
<input type="email" id="email" name="email" placeholder="e-mail" required onclick="valideer(this)">
</div>
</div>
<!--einde span7-->
</div>
<div class="span4 valid">
<div id="msgbox1" class="alert alert-error">
<div class="span1">
</div>
</div>
</div>
<div class="span1">
<div class="span1">
</div>
<!--einde row-->
</div>
<!--einde container-->
</div>
</div>
</fieldset>
<fieldset>
<div class="container">
<div class="row">
<div class="span7">
<div class="control-group">
<div class="controls">
</div>
</div>
<div class="control-group">
<div class="controls">
</div>
</div>
<div class="control-group">
<div class="controls">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success" onclick="valideer(this)">Verzenden</button>
</div>
</div>
<div class="span4 valid">
<div id="msgbox3" class="alert alert-success"></div>
</div>
<div class="span1">
<!--lege kolom-->
</div>
<!--einde row-->
</div>
<!--einde container-->
</div>
</fieldset>
</form>
</section>
<footer class="container">
<p>© 2013 The Wood Factory </p>
</footer>
</body>
</html>
Some notes and observations:
Since the only check being used for validation is if it contains, an empty string, I have generalised the valideer function to iterate and operate on a given array of ids. This can be made even better by querying for inputs on your form using a DOM query and handling it like that.
You have added a lot of inline event handlers in your dom.. Some of them are redundant and not really needed. For example, having a simgle onsubmit on your form element should suffice (no need to add it for every input inside the form)
You were using a global variable list2 this is what was causing the repeated entries each time you click the button. Localising the scope would fix that (by moving it inside a function)
You're already using required property, which means you no longer need a js function to validate if your inputs are empty or not.
You should also notice that list2 is a global variable, which means that you should clean it at the end of every valideer() invocation.
All in all, you code seems very verbose .. try to find a better way to express you needs.

Form validation with multiple highlighted fields

I have a registration form that I would like to have multiple field validation. What I mean by this is if more than one field is not filled in it will be highlighted red. I have some code already written but instead of highlighting the field not filled in, it's highlighting all of them. I realise it is quite long winded but I'm fairly new to this. My JS code is as follows:
`function formCheck() {
var val = document.getElementById("fillMeIn").value;
var val = document.getElementById("fillMeIn2").value;
var val = document.getElementById("fillMeIn3").value;
var val = document.getElementById("fillMeIn4").value;
var val = document.getElementById("fillMeIn5").value;
var val = document.getElementById("fillMeIn6").value;
var val = document.getElementById("fillMeIn7").value;
if (val == "") {
alert("Please fill in the missing fields");
document.getElementById("fillMeIn").style.borderColor = "red";
document.getElementById("fillMeIn2").style.borderColor = "red";
document.getElementById("fillMeIn3").style.borderColor = "red";
document.getElementById("fillMeIn4").style.borderColor = "red";
document.getElementById("fillMeIn5").style.borderColor = "red";
document.getElementById("fillMeIn6").style.borderColor = "red";
document.getElementById("fillMeIn7").style.borderColor = "red";
return false;
}
else {
document.getElementById("fillMeIn").style.borderColor = "green";
document.getElementById("fillMeIn2").style.borderColor = "green";
document.getElementById("fillMeIn3").style.borderColor = "green";
document.getElementById("fillMeIn4").style.borderColor = "green";
document.getElementById("fillMeIn5").style.borderColor = "green";
document.getElementById("fillMeIn6").style.borderColor = "green";
document.getElementById("fillMeIn7").style.borderColor = "green";
}
}`
My HTML is as follows:
'<form id="mbrForm" onsubmit="return formCheck();" action="thanks.html" method="post">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
FIRST NAME:
<input id="fillMeIn" type="text" class="form-control" placeholder="First Name" >
</div>
<div class="col-md-4 vertical-gap">
LAST NAME:
<input id="fillMeIn2" type="text" class="form-control" placeholder="Last Name" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 vertical-gap">
ADDRESS:
<input id="fillMeIn3" type="text" class="form-control vertical-gap" placeholder="First Line" >
<input id="fillMeIn4" type="text" class="form-control vertical-gap" placeholder="Second Line" >
<input id="fillMeIn5" type="text" class="form-control vertical-gap" placeholder="Town/City" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
POST CODE:
<input id="fillMeIn6" type="text" class="form-control vertical-gap" placeholder="Postcode" >
</div>
<div class="col-md-4 vertical-gap">
PHONE No:
<input type="number" class="form-control vertical-gap" placeholder="Tel no">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
EMAIL ADDRESS:
<input id="fillMeIn7" type="email" class="form-control vertical-gap" placeholder="Email address" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row vertical-gap">
<div class="col-md-2"></div>
<div class="col-md-8">
DISCIPLINE:
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Cross Country"> CROSS COUNTRY
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Enduro"> ENDURO
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Downhill"> DOWNHILL
</label>
</div>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-10">
<!--<button type="button" input type="hidden" class="btn btn-success" name="redirect" value="thanks.html">SUBMIT</button>-->
<input type="submit" value="SUBMIT" class="btn btn-success btn-lg">
</div>
<div class="col-md-2"></div>
</div>
</form>'
Thanks!
You could have the ids in an Array, iterate through its values, and execute the repeatable code in a function that groups all the logic inside.
example :
["fillMeIn1", "fillMeIn2", "fillMeIn3", "fillMeIn4"].each(function(id){
// do things with id
})
Why not use the html "required" property instead?
If you want to do this with JS, you should give each variable a different name. In the code you posted you are continuously overwriting the same variable, and then, it evaluates val (which ended up being assigned to the (fill me7 value) to "", and if true, setting all the borders to red.
Set different variables, push the input values into an array when submit is triggered and loop through them if variables[i]==0, set getElementId(switch case[i] or another array with the name of the inputs[i]).bordercolor to red.
AGAIN, this sound VERY INEFFICIENT and I am not sure at all it would work. My guess is that it would take A LOT of time, and probably get timed out (except you are using some asych/try-catch kind of JS).
I would simply go for an HTML required property and then override the "required" property in CSS to make it look as you intend to. Simpler, easy and clean.
The main issue in your code is that you override the variable val each time you wrote var val = ....
Keeping your own your logic, you could write something like that.
var formModule = (function () {
var $fields = [
document.getElementById('fillMeIn'),
document.getElementById('fillMeIn2'),
document.getElementById('fillMeIn3'),
document.getElementById('fillMeIn4'),
document.getElementById('fillMeIn5'),
document.getElementById('fillMeIn6'),
document.getElementById('fillMeIn7')
];
function markInvalid($field) {
$field.style.borderColor = 'red';
}
function markValid($field) {
$field.style.borderColor = 'green';
}
return {
check: function () {
var isValid = true;
$fields.forEach(function ($f) {
if ($f.value === '') {
if (isValid) alert('Please fill in the missing fields');
isValid = false;
markInvalid($f);
}
else markValid($f);
});
return isValid;
}
};
})();
There are some extra concepts in this example which may be useful:
Working with the DOM is really slow, that's why you should
put your elements in a variable once for all and not everytime you
click on the submit button.
In my example i wrap the code with var formModule = (function () {...})();.
It's called module pattern. The goal is to prevent variables to leak in the rest of the application.
A better solution could be this one using the 'power' of html form validation:
HTML:
<form id="mbrForm" action="thanks.html" method="post">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
FIRST NAME:
<input id="fillMeIn" type="text" required class="form-control" placeholder="First Name">
</div>
<div class="col-md-4 vertical-gap">
LAST NAME:
<input id="fillMeIn2" type="text" required class="form-control" placeholder="Last Name">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 vertical-gap">
ADDRESS:
<input id="fillMeIn3" type="text" required class="form-control vertical-gap" placeholder="First Line">
<input id="fillMeIn4" type="text" required class="form-control vertical-gap" placeholder="Second Line">
<input id="fillMeIn5" type="text" required class="form-control vertical-gap" placeholder="Town/City">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
POST CODE:
<input id="fillMeIn6" type="text" required class="form-control vertical-gap" placeholder="Postcode">
</div>
<div class="col-md-4 vertical-gap">
PHONE No:
<input type="number" class="form-control vertical-gap" placeholder="Tel no">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
EMAIL ADDRESS:
<input id="fillMeIn7" type="email" required class="form-control vertical-gap" placeholder="Email address">
</div>
<div class="col-md-2"></div>
</div>
<div class="row vertical-gap">
<div class="col-md-2"></div>
<div class="col-md-8">
DISCIPLINE:
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Cross Country"> CROSS COUNTRY
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Enduro"> ENDURO
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Downhill"> DOWNHILL
</label>
</div>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-10">
<input id="btnSubmit" type="submit" value="SUBMIT" class="btn btn-success btn-lg">
</div>
<div class="col-md-2"></div>
</div>
</form>
JS:
var formModule = (function () {
var $form = document.getElementById('mbrForm');
var $btn = document.getElementById('btnSubmit');
var $fields = [
document.getElementById('fillMeIn'),
document.getElementById('fillMeIn2'),
document.getElementById('fillMeIn3'),
document.getElementById('fillMeIn4'),
document.getElementById('fillMeIn5'),
document.getElementById('fillMeIn6'),
document.getElementById('fillMeIn7')
];
checkValidation();
$form.addEventListener('change', checkValidation);
$form.addEventListener('keyup', checkValidation);
$fields.forEach(function ($f) {
$f.addEventListener('change', function () {
markInput($f, $f.checkValidity());
});
});
function checkValidation() {
$btn.disabled = !$form.checkValidity();
}
function markInput($field, isValid) {
$field.style.borderColor = isValid ? 'green' : 'red';
}
})();
In this example, the button gets disabled until the form is valid and inputs are validated whenever they are changed.
I added required attribute in HTML inputs so they can be handled by native javascript function checkValidity(). Note that in this case inputs email and number are also correctly checked. You could also use attribute pattern to get a more powerfull validation:
<input type="text" pattern="-?[0-9]*(\.[0-9]+)?">
Hope it helps.

ng-model not updating with input from textbox

This seems like a weird one to me. I have a form for adding vets to a dog walkers' database. I've used ng-model on each field in the form.
<div class="container-fluid" ng-show="nav.page == 'new'" ng-controller="dataController as data">
<div class="row" ng-show="nav.tab == 'vet'">
<div class="col-md-2">
</div>
<div class="col-md-8">
<h1>Add a Vet</h1>
<hr />
<form>
<div class="form-group">
<input type="text" class="form-control" placeholder="Name..." ng-model="data.creator.vet.Name"/>
</div>
<div class="form-group">
<input type="Text" class="form-control" placeholder="Address..." ng-model="data.creator.vet.Address"/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Phone Number..." ng-model="data.creator.vet.Phone"/>
</div>
<div class="form-group">
<button class="btn btn-success" ng-click="data.newVet()">Submit</button>
</div>
</form>
</div>
<div class="col-md-2">
</div>
</div>
</div>
Yesterday it was working fine, today it won't update data.creator.vet when I input data. For the life of me, I can't see any problems with it.
The js:
app.controller('dataController', function($http) {
dataCon = this;
this.creator = {};
this.creator.client = {};
this.creator.vet = {};
this.creator.client.Dogs = [];
this.allData = {};
this.newVet = function(){
console.log("New Vet Creating....")
console.log(dataCon.creator)
vet = JSON.stringify(dataCon.creator.vet);
console.log(vet);
$http.get(SERVICE_URL + "?fn=vetCreate&vet=" + vet).then(function(response) {
dataCon.init();
});
}
});

Validation of code

I have developed some code in bootstrap and I am getting an error while I was validating the fields (name, email). Please help me out.
This is the code for the form:
<div class="container">
<h3 class="text-center">CONTACT</h3>
<p class="text-center"><em>I love my Fans!</em></p>
<div class="row test">
<div class="col-md-4">
<p><span class="glyphicon glyphicon-map-marker"></span>4429, Rainier Street, Irving, Texas ,United States</p>
<p><span class="glyphicon glyphicon-phone"></span>Phone:Phone</p>
<p><span class="glyphicon glyphicon-envelope"></span>Email: Email</p>
</div>
<div class="col-md-8">
<div class="row">
<div class="col-sm-6 form-group">
<input class="form control" id="name" placeholder="Name" type="text" onBlur="txt_Blur(this,'errorName')" />
<span id="errorName" style="display:none;">Please enter a valid name!</span>
</div>
<div class="col-sm-6 form-group">
<input class="form control" id="email" name="email" placeholder="Email" type="email" required>
<span id="errorName" style="display:none;">Please enter a valid email!</span>
</div>
</div>
<div class="textarea">
<textarea class="form-control" id="comments" name="comments" placeholder="Comment" rows="5"></textarea>
<span id="errorName" style="display:none">Please enter your comments!</span>
</div>
<br>
<div class="row">
<div class="col-md-12 form-group">
<button class="btn pull-right" type="submit" onclick="button_Click()">Send</button>
</div>
</div>
</div>
</div>
</div>
The JavaScript for validation below:
function txt_Blur(ref, errorId) {
if (ref.value == "") {
document.getElementById(errorId).style = "color:red;";
} else {
document.getElementById(errorId).style = "display:none;";
}
}
function button_Click() {
if (document.getElementById("name")).value == "") {
document.getElementById("errorName").style = "color:red;";
} else {
document.getElementById("errorName").style = "display:none;";
}
if (document.getElementById("email")).value == "") {
document.getElementById("errorName").style = "color:red;";
} else {
document.getElementById("errorName").style = "display:none;";
}
}
I need the error displayed when someone tries to leave the name field empty and goes to the next text field (email).

Categories