Javascript multiple email regexp validation - javascript

Normally validation of simple email is:
/^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
This will validate email like test#test.com
But how to validate if email is multiple?
entry 1: test#test.com, test1#test.com, test2#test.com
entry 2: test#test.com , test1#test.com , test2#test.com
entry 3: test#test.com, test1#test.com , test2#test.com
entry 4: test#test.com
This emails is a possible entries that user will input. Also expect thier is 2 or 3 or 4 or more emails sometimes.
Thanks for the answers.

Split the emails on a comma and validate the entries
var x = getEmails();
var emails = x.split(",");
emails.forEach(function (email) {
validate(email.trim());
});
Where getEmails() gets the emails from the page, and validate runs your regex against the emails

try this
function validateEmails(string) {
var regex = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var result = string.replace(/\s/g, "").split(/,|;/);
for(var i = 0;i < result.length;i++) {
if(!regex.test(result[i])) {
return false;
}
}
return true;
}
accept both comma and semicolon as separator

Here is a regex for multiple mail validation without split
function validateMultipleEmails(string) {
var regex = /^([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-\.]+)+([;]([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-\.]+))*$/;
return regex.test(string);
}
https://regex101.com/r/TUXLED/1

You should be able to split the entry by commas, and then test the individual email subentries against the regexp.
var valid = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var entries = entry.split(",");
if(valid.test(entries[0]))... //or however your testing against the regex
You might also want to trim any whitespace before testing any of the stripped email substrings.

Try this for jquery validation:
jQuery.validator.addMethod("multiemail", function (value, element) {
if (this.optional(element)) {
return true;
}
var emails = value.split(','),
valid = true;
for (var i = 0, limit = emails.length; i < limit; i++) {
value = emails[i];
valid = valid && jQuery.validator.methods.email.call(this, value, element);
}
return valid;
}, "Invalid email format: please use a comma to separate multiple email addresses.");

function validateEmail(emailAddress) {
var emailPattern = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return emailPattern.test(emailAddress);
}
function validate() {
$("#result").text("");
var email = $("#emailAddress").val();
if (validateEmail(email)) {
$("#result").text(email + " validation successful");
$("#result").css("color", "white");
} else {
$("#result").text(email + " validation failed");
$("#result").css("color", "red");
}
return false;
}
$("form").bind("submit", validate);
.divSection{
text-align: center; padding: 8%;
}
.pSection{
border: none; color: white; padding: 10px 100px; text-align: center; text-decoration: none; display: inline-block; font-size: 24px; margin: 3% 0%; border-radius: 6px; -webkit-transition-duration: 0.4s; transition-duration: 0.4s; font-family: Roboto-Regular,Helvetica,Arial,sans-serif; background-color: #4184f3; margin: auto;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divSection">
<form action="dashboard/user/profile" method="POST">
<input id="emailAddress" placeholder="Enter Email" value="shubham20.yeole#gmail.com">
<input type='submit' value="check">
</form>
</div>
<div class="divSection" >
<p class="pSection" id='result'></p>
</div>
This is javascript code to check if email contains more than one # characters
var count=0;
email = "shubham20.ye#ole#gmail.com";
alert(email);
for(i =0; i<email.length;i++){
if(email.charAt(i) == "#"){
count++;
}}
if(count>1){
alert("not ok")
} else {
alert("ok")
}
Alternate way is by using the standard pattern of the email
var pattern= /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
re.test(email);

Javascript multiple email regexp validation in ruby dynamic data
<span id="error_message_<%= item.id %>" class="p-3 mb-2 text-danger text-center">Multiple emails must be separated by comma.</span>
<%= text_field_tag :email, nil, style: 'width: 60%;', required: true, id: "emails_#{item.id}", placeholder: "Multiple emails must be separated by comma." %>
$(document).ready(function() {
document.getElementById("cc_submit_<%= item.id %>").disabled = true;
document.getElementById('error_message_<%= item.id %>').style.display='none';
});
$('#emails_<%= item.id %>').keyup( function() {
var emails = $('#emails_<%= item.id %>').val();
var emails = emails.split(",");
var valid = true;
var regex = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var invalidEmails = [];
for (var i = 0; i < emails.length; i++) {
emails[i] = emails[i].trim();
if( emails[i] == "" || ! regex.test(emails[i])){
invalidEmails.push(emails[i]);
}
}
if(invalidEmails != 0) {
document.getElementById("cc_submit_<%= item.id %>").disabled = true;
document.getElementById("error_message_<%= item.id %>").style.display='block';
}
else{
document.getElementById("cc_submit_<%= item.id %>").disabled = false;
document.getElementById('error_message_<%= item.id %>').style.display='none';
}
})

Related

How should I include these functions in AllValidate function?

When click on the submit button, I want to make sure it can detect if the user correctly entered the forms through the functions below, if user did not enter correctly it can stop the form from being submit.
What should I include in my AllValidate function?*
<button name="regbtn" id="register_btn" class="reg_btn" type="submit" onclick="AllValidate()">Register</button>
function addressValidate()
{
var address = document.getElementById("reg_add").value;
var space = /^\s*$/;
var flag = true;
if(address.match(space))
{
document.getElementById("add_error").innerHTML = "Address is required.";
document.getElementById("reg_add").style.border = "2px solid red";
flag = true;
}
else
{
document.getElementById("add_error").innerHTML = "";
document.getElementById("reg_add").style.border = "2px solid #f0f0f0";
flag = false;
}
return flag;
}
function phoneValidate()
{
var phoneNo = document.getElementById("reg_phone").value;
var pattern = /[0-9]{3}-[0-9]{4}-[0-9]{4}/;
var space = /^\s*$/;
var flag = true;
if(phoneNo.match(space))
{
document.getElementById("phone_error").innerHTML = "Phone number is required.";
document.getElementById("reg_phone").style.border = "2px solid red";
flag = true;
}
else if(phoneNo.match(pattern))
{
document.getElementById("phone_error").innerHTML = "";
document.getElementById("reg_phone").style.border = "2px solid #f0f0f0";
flag = false;
}
else
{
document.getElementById("phone_error").innerHTML = "Please enter a valid phone number.";
document.getElementById("reg_phone").style.border = "2px solid red";
flag = true;
}
return flag;
}
AllValidate()
{
}
First you have to edit the submit button as follows
<button name="regbtn" id="register_btn" class="reg_btn" type="submit" onclick="return AllValidate()">Register</button>
Then your AllValidate() function follows
function AllValidate(){
return (addressValidate() && phoneValidate());
}
use that way, with HTML5 auto validation
use attribute required
use attribute pattern ( you can also use input type="tel")
sample code
// personnalize your error message
const myForm = document.forms['my-form']
myForm.reg_phone.oninvalid=_=>
{
let msg = (myForm.reg_phone.value.trim() === '')
? 'Phone number is required.'
: 'Please enter a valid phone number.'
myForm.reg_phone.setCustomValidity(msg)
}
// just to verify input...
myForm.onsubmit = evt =>
{
evt.preventDefault() // just for test here (disable submit)
// shwo values
console.clear()
console.log( 'name :' , myForm.reg_name.value )
console.log( 'address :' , myForm.reg_add.value )
console.log( 'Phone :' , myForm.reg_phone.value )
}
form {
display: flex;
flex-direction: column;
width: 18em;
}
label {
display: block;
margin-top: .7em;
}
label * {
vertical-align: baseline;
}
label input,
label textarea {
display: block;
float: right;
font-size:1.2em;
padding: .2em;
}
label input {
width: 9em;
}
button {
margin: 2em;
font-weight: bold;
}
<form action="..." name="my-form">
<label>
name :
<input type="text" name="reg_name" required>
</label>
<label>
address :
<textarea name="reg_add" rows="4" required placeholder="address"></textarea>
</label>
<label>
Phone :
<input type="text" name="reg_phone" required pattern="\d{3}-\d{4}-\d{4}" placeholder="___-____-____">
</label>
<button type="submit">Register</button>
</form>

How can I use this in a loop?

I'm doing this for a class assignment and I know there has to be a better way of writing it. Maybe some kind of loop that gets the inputs and labels? I'm repeating a lot here and it seems better to minify this if possible.
function checkEmptyFields() {
if(formName.value === "") {
formLabels[0].classList.add("has-errors");
formLabels[0].innerHTML = "Name is required *";
formName.style.borderBottomColor = "red";
} else {
formLabels[0].classList.remove("has-errors");
formLabels[0].innerHTML = "Name";
formName.style.borderBottomColor = "green";
}
if(formEmail.value === "") {
formLabels[1].classList.add("has-errors");
formLabels[1].innerHTML = "Email is required *";
formEmail.style.borderBottomColor = "red";
} else {
formLabels[1].classList.remove("has-errors");
formLabels[1].innerHTML = "Email";
formEmail.style.borderBottomColor = "green";
}
if(formNumber.value === "") {
formLabels[2].classList.add("has-errors");
formLabels[2].innerHTML = "Phone is required *";
formNumber.style.borderBottomColor = "red";
} else {
formLabels[2].classList.remove("has-errors");
formLabels[2].innerHTML = "Phone";
formNumber.style.borderBottomColor = "green";
}
if(formMessage.value === "") {
formLabels[3].classList.add("has-errors");
formLabels[3].innerHTML = "message is required *";
formMessage.style.borderBottomColor = "red";
} else {
formLabels[3].classList.remove("has-errors");
formLabels[3].innerHTML = "Email";
formMessage.style.borderBottomColor = "green";
}
}
You can try like this:
fields = [{
'name': formName,
'index': 0,
'css-error': "has-errors",
'innerHtml': "Name",
'innerHtml-error': "Name is required *",
'borderBottomColor ': "green", //Or you can hardcode it in the loop itself.
'borderBottomColor-error': "red"
},
....
]
for(var i=0; i < fields.length; i++) {
var field = fields[i];
if(field.name.value == "") {
formLabels[field.index].classList.add(field.css);
formLabels[field.index].innerHTML = field.innerHtml-error;
field.name.style.borderBottomColor = field.borderBottomColor-error ;
} else {
formLabels[field.index].classList.remove(field.css);
formLabels[field.index].innerHTML = field.innerHtml;
field.name.style.borderBottomColor = field.borderBottomColor ;
}
}
You can create arrays for both the controls and the control names, and process them together with the formLabels array that you already have, in a for-loop that goes from 0 to length (not inclusive), like this:
function checkEmptyFields() {
var controls = [formName, formEmail, formNumber, formMessage];
var controlNames = ["Name", "Email", "Phone", "Message"];
for (var i = 0; i < controls.length; i++) {
if(controls[i].value === "") {
formLabels[i].classList.add("has-errors");
formLabels[i].innerHTML = controlNames[i] + " is required *";
controls[i].style.borderBottomColor = "red";
} else {
formLabels[i].classList.remove("has-errors");
formLabels[i].innerHTML = controlNames[i];
controls[i].style.borderBottomColor = "green";
}
}
}
You can write an additional function to check one field:
function checkEmptyField(field, ind, msg, errmsg) {
if(field.value === "") {
formLabels[ind].classList.add("has-errors");
formLabels[ind].innerHTML = errmsg;
field.style.borderBottomColor = "red";
} else {
formLabels[ind].classList.remove("has-errors");
formLabels[ind].innerHTML = msg;
field.style.borderBottomColor = "green";
}
}
Then you can call it
function checkEmptyFields() {
checkEmptyField(formName,0,"Name","Name is required *");
...
If you know about and understand for loops you can simply loop over 2 arrays of data like this:
function checkEmptyFields() {
formArray = [formName, formEmail, formNumber, formMessage];
labelArray = ["Name", "Email", "Phone", "Message"];
for (let i = 0; i < formArray.length; i++) {
if(formArray[i].value === "") {
formLabels[i].classList.add("has-errors");
formLabels[i].innerHTML = labelArray[i] + " is required *";
formArray[i].style.borderBottomColor = "red";
} else {
formLabels[i].classList.remove("has-errors");
formLabels[i].innerHTML = labelArray[i];
formArray[i].style.borderBottomColor = "green";
}
}
}
if not then you can read about them here:
https://www.w3schools.com/js/js_loop_for.asp
Anytime you have roughly the same code in more than one place, you should stop and rethink your approach as you are doing here.
If you give each of the HTML elements that need to be validated a common class, you can then create a node list (collection/array) that contains them. Then you can loop over that collection and perform the same test (written only once) on each item and act accordingly.
Also, I'm not quite sure what you are doing with .innerHTML, but don't use that when the text you are working with doesn't have any HTML in it. .innerHTML has security and performance implications. Instead, use .textContent when there is no HTML.
// Get all the form fields that need validation into an Array
let fields = Array.prototype.slice.call(document.querySelectorAll(".validationNeeded"));
// Set up form submit event handler
document.querySelector("form").addEventListener("submit", checkEmptyFields);
function checkEmptyFields(event) {
let validCount = fields.length; // Holds the number of valid fields
// Loop over the array
fields.forEach(function(field){
if(field.value === ""){
field.previousElementSibling.classList.add("has-errors-label"); // style the label
field.classList.add("has-errors-field"); // style the field
field.classList.remove("valid-field"); // style the field
validCount--; // Decrease the count of valid fields
} else {
field.previousElementSibling.classList.remove("has-errors-label"); // style the label
field.classList.remove("has-errors-field"); // style the field
field.classList.add("valid-field"); // style the field
}
});
// Check to see if the form should be submitted
if(validCount !== fields.length){
event.preventDefault(); // Cancel the form's submission
}
}
.row {margin-bottom:5px; }
.has-errors-label { color:red; }
.has-errors-field { outline:1px solid red; }
.valid-field { outline:1px solid green; }
<form action="#" method="get">
<div class="row">
<label for="userName">Name: </label>
<input class="validationNeeded" name="userName" id="userName">
</div>
<div class="row">
<label for="email">Email: </label>
<input class="validationNeeded" name="email" id="email">
</div>
<div class="row">
<label for="phone">Phone: </label>
<input class="validationNeeded" name="phone" id="phone">
</div>
<button>Submit</button>
</form>

username is not a part of password and vice versa javascript or jquery

Password should not contain username or parts of the user's full name that exceed two consecutive characters
If username= 1Abcd234
password= aBc15
then it should return error like password could not contain any parts of username.
Because "abc1" is present in both password and username.
I think you could use something like this:
function FindIntersectionFromStart(a,b){
for(var i=a.length;i>0;i--){
d = a.substring(0,i);
j = b.indexOf(d);
if (j>=0){
return ({position:j,length:i});
}
}
return null;
}
function FindIntersection(a,b){
var bestResult = null;
for(var i=0;i<a.length-1;i++){
var result = FindIntersectionFromStart(a.substring(i),b);
if (result){
if (!bestResult){
bestResult = result;
} else {
if (result.length>bestResult.length){
bestResult = result;
}
}
}
if(bestResult && bestResult.length>=a.length-i)
break;
}
return bestResult;
}
var username = "myUsername";
var password = "myuse";
result = FindIntersection(username.toLowerCase(), password.toLowerCase());
if(result.length > 2){
console.log("Invalid Password!");
} else {
console.log("Valid Password!")
}
Here's a simple approach (may not be the best though):
First get all combinations of consecutive characters from username that should not be found in password. This would depend on the number of consecutive characters that your application considers invalid if matched.
Now, run a simple loop and check the presence of any of the invalid combinations using String.indexOf method.
Make sure that you convert both - username and password to same case for simplicity.
$("#check").on("click", checkValidity );
function checkValidity(){
var numConsecutiveChars = 2;
var username = $("#username").val().trim().toLowerCase();
var password = $("#password").val().trim().toLowerCase();
// first find all combinations that should not be found in password
var invalidCombinations = [];
for( var i = 0; i < username.length - numConsecutiveChars; i++ ){
var curCombination = username[i] + username[i+1];
invalidCombinations.push( curCombination );
}//for
// now check all invalidCombinations
var invalid = false;
for( var i = 0; i < invalidCombinations.length; i++ ){
var curCombination = invalidCombinations[i];
if( password.indexOf( curCombination ) !== -1 ){
invalid = true;
break;
}
}//for()
if( invalid ){
alert("Invalid password");
}else{
alert("Valid password");
}
}//checkValidity()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="username" value="user" />
<input type="text" id="password" value="pass" />
<button id="check">Check validity</button>

R flexdashboard and log-in form

I have a flexdashboard, which is not hosted on a server and I use it as a local html file.
However, I need the content of the HTML to be password protected. I know i can use win-zip, but I was wondering if it would be possible to integrate a simple log-in form with a global username & password.
My attempt:
---
title: "Dashboard"
output:
flexdashboard::flex_dashboard:
vertical_layout: scroll
logo: logo.jpg
shiny: include
---
```{r}
branch <- "test"
num_entries <- 3
```
<style>
.navbar {
background-color:red;
border-color:black;
}
.navbar-inverse .navbar-nav>.active>a, .navbar-inverse .navbar-nav>.active>a:hover, .navbar-inverse .navbar-nav>.active>a:focus {
color: black;
background-color: #feb0b0;
}
.navbar-inverse .navbar-nav > li > a:hover, .navbar-inverse .navbar-nav > li > a:focus {
background-color: #feb0b0
}
</style>
<script type = "text/javascript">
// Note: Like all Javascript password scripts, this is hopelessly insecure as the user can see
//the valid usernames/passwords and the redirect url simply with View Source.
// And the user can obtain another three tries simply by refreshing the page.
//So do not use for anything serious!
var count = 2;
function validate() {
var un = document.myform.username.value;
var pw = document.myform.pword.value;
var valid = false;
var unArray = ["Philip", "George", "Sarah", "Michael"]; // as many as you like - no comma after final entry
var pwArray = ["Password1", "Password2", "Password3", "Password4"]; // the corresponding passwords;
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert ("Login was successful");
window.location = "http://www.google.com";
return false;
}
var t = " tries";
if (count == 1) {t = " try"}
if (count >= 1) {
alert ("Invalid username and/or password. You have " + count + t + " left.");
document.myform.username.value = "";
document.myform.pword.value = "";
setTimeout("document.myform.username.focus()", 25);
setTimeout("document.myform.username.select()", 25);
count --;
}
else {
alert ("Still incorrect! You have no more tries left!");
document.myform.username.value = "No more tries allowed!";
document.myform.pword.value = "";
document.myform.username.disabled = true;
document.myform.pword.disabled = true;
return false;
}
}
</script>
<form name = "myform">
<p>ENTER USER NAME <input type="text" name="username"> ENTER PASSWORD <input type="password" name="pword">
<input type="button" value="Check In" name="Submit" onclick= "validate()">
</p>
</form>
```{r setup, include=FALSE}
library(flexdashboard)
```
Overview {data-orientation=columns}
=====================================
This however, doesn't work, as the username and password appear togather with the dashboard content and not hide it by acting as a landing page.
Any ideas how I can fix this?

Validating Input with Javascript

I'm working on a web form with several textboxes and a submit button. When the submit button is clicked, I am supposed to verify that the required fields all have input and that the age field is only numeric. For example, the user can enter 56, but 56 years-old, shouldn't be accepted. If the user enters invalid input or leaves required fields blank, the border around the appropriate textboxes should turn red.
However, as my code is written now all the required fields turn red regardless of input. Any ideas how I can fix this and make the page follow the couple of rules I listed?
Most Recent Code
<html>
<head>
<title>Project 4</title>
<style type="text/css">
body {
background-color: black;
color: blue;
text-align: center;
border: 2px double blue;
}
</style>
</head>
<body>
<h1>Welcome to my Web Form!</h1>
<p>
Please fill out the following information.<br>
Please note that fields marked with an asterisk (*) are required.
</p>
<form name="myForm" id="myForm" onsubmit="return validateForm()">
*Last Name: <br>
<input type="text" id="lastname">
<br>
First Name: <br>
<input type="text" id="firstname">
<br>
*Hobbies (separate each hobby with a comma): <br>
<input type="text" id="hobbies">
<br>
Pets:
<div id="petsContainer">
<input type="text" id="pets">
<input type="button" id="addPet" value="Add Pet">
</div>
<br>
Children:
<div id="childContainer">
<input type="text" id="children">
<input type="button" id="addKid" value="Add Child">
</div>
<br>
*Address: <br>
<input type="text" id="address">
<br>
*Phone Number:<br>
<input type="text" id="phone">
<br>
*Age: <br>
<input type="text" id="age">
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
var validatePhoneOnKeyUpAttached = false;
var validateLNameOnKeyUpAttached = false;
var validateHobbiesOnKeyUpAttached = false;
var validateAddressOnKeyUpAttached = false;
var validateAgeOnKeyUpAttached = false;
function validateForm() {
if(!validatePhoneOnKeyUpAttached) {
document.getElementById("phone").onkeyup = checkPhone;
validatePhoneOnKeyUpAttached = true;
}
else if(!validateLNameOnKeyUpAttached) {
document.getElementById("lastname").onkeyup = checkEmpty;
validateLNameOnKeyUpAttached = true;
}
else if(!validateHobbiesOnKeyUpAttached) {
document.getElementById("hobbies").onkeyup = checkEmpty;
validateHobbiesOnKeyUpAttached = true;
}
else if(!validateAddressOnKeyUpAttached) {
document.getElementById("address").onkeyup = checkEmpty;
validateAddressOnKeyUpAttached = true;
}
else if(!validateAgeOnKeyUpAttached) {
document.getElementById("age").onkeyup = checkEmpty;
document.getElementById("age").onkeyup = checkAge;
validateAgeOnKeyUpAttached = true;
}
return checkEmpty() && checkPhone() && checkAge();
}
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {
document.getElementById("phone").style.borderColor="transparent";
return true;
}
else if(phoneNum.length < 7 || phoneNum.length > 10) {
document.getElementById("phone").style.borderColor="red";
return false;
}
}
function checkEmpty() {
var lname = document.forms["myForm"]["lastname"].value;
var pNum = document.forms["myForm"]["phone"].value;
var hobs = document.forms["myForm"]["hobbies"].value;
var live = document.forms["myForm"]["address"].value;
var yr = document.forms["myForm"]["age"].value;
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("hobbies").style.borderColor = (hobs == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
document.getElementById("address").style.borderColor = (live == "") ? "red" : "transparent";
document.getElementById("age").style.borderColor = (yr == "") ? "red" : "transparent";
}
function checkAge() {
var age = document.getElementById("age").value;
if(isNan(age)) {
return false;
}
else {
document.getElementById("age").style.borderColor="red";
return true;
}
}
document.getElementById("addPet").onclick=function() {
var div = document.getElementById("petsContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "pats[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
document.getElementById("addKid").onclick=function() {
var div = document.getElementById("childContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "child[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
</script>
</body>
</html>
The problem I'm currently having is that when I click the submit button, all the fields turn red for a split second, but then go back to the regular color and the input is erased. Any thoughts on how to fix this?
By including all of the borderColor="red" statements in a single code block, you're applying that style to all your inputs, even if only one of them failed validation. You need to separate out each statement so that it only applies to the individual field(s) that failed validation:
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
...
Also, I'm using the ternary operator ? : to clean up the code as well. These statements would replace the if-else block you've written.
I am using the following javascript functions in order to validate my form variables. Hope these will helpful for you.
var W3CDOM = (document.getElementsByTagName && document.createElement);
window.onload = function () {
document.forms[0].onsubmit = function () {
return validate()
}
}
function validate() {
validForm = true;
firstError = null;
errorstring = '';
var x = document.forms[0].elements;
for (var i = 0;i < x.length;i++) {
if (!x[i].value) {
validForm = false;
writeError(x[i], 'This field is required');
}
}
// This can be used to validate input type Email values
/* if (x['email'].value.indexOf('#') == -1) {
validForm = false;
writeError(x['email'],'This is not a valid email address');
}
*/
if (!W3CDOM)
alert(errorstring);
if (firstError)
firstError.focus();
return validForm;
}
function writeError(obj, message) {
validForm = false;
//if (obj.hasError) return false;
if (W3CDOM) {
obj.className += ' error';
obj.onchange = removeError;
var sp = document.createElement('span');
sp.className = 'error';
sp.appendChild(document.createTextNode(message));
obj.parentNode.appendChild(sp);
obj.hasError = sp;
} else {
errorstring += obj.name + ': ' + message + '\n';
obj.hasError = true;
}
if (!firstError)
firstError = obj;
return false;
}
function removeError() {
this.className = this.className.substring(0, this.className.lastIndexOf(' '));
this.parentNode.removeChild(this.hasError);
this.hasError = null;
this.onchange = null;
}
You can call the validations right after the form submission as given below.
<form name="loginForm" action="do.login" method="POST" class="form" onsubmit="return validate();">

Categories