This RegEx for an email passes on http://scriptular.com, but fails all the browsers. Any ideas why? i tried a number of ways; but at this point, I am clueless.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>RegEx Test</title>
<script type="text/javascript">
function saveSignUp(){
var warning = "The following field(s) require an entry: \n \n";
var same = warning;
var email = document.forms[0].email.value;
// FIRST TEST
/*var regExEmail= /^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+/;*/
// SECOND TEST
var regExEmail= /[a-zA-Z0-9_.-]+#[a-zA-Z0-9_.-]+\.[a-zA-Z]+/;
if(email == ""){ warning += " - Email is required \n"; }
else if(email != regExEmail){ warning += " - E-mail not formatted properly \n"; }
if (warning == same){
return true;
}
else {
alert(warning);
}
return false;
}
</script>
</head>
<body>
<form method="post" onsubmit="return saveSignUp()" action="signupSucces.html" >
<input type="text" placeholder="Email" name="email">
<input type="submit" class="button wide" value="Request an Account">
</form>
</body>
</html>
if(email != regExEmail)
This is not how you test a regex match. Use this instead:
if (!regExEmail.test(email))
And, you should encose your regex within ^..$ to check the whole string matches, not just a substring of it.
var regExEmail= /^[a-zA-Z0-9_.-]+#[a-zA-Z0-9_.-]+\.[a-zA-Z]+$/;
Related
i have a formset inside my form on django and i need to do a button add to offer to the user the possibility to fill the fields of the formset as many time as he wants. i used a javascript code to do that and i do all the following steps to link the js file with the project, but when i click on the button nothing happens, i don't know why. please if anyone could help me.
i add staticfiles on my settings
STATIC_URL = '/static/'
STATICFILES_DIRS = (BASE_DIR / "static",)
part of my html file
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ordonnancement </title>
...
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body class="bg-gray-100">
<form action="/" method="post" class="join-form mt-8 m-auto">
{% csrf_token %}
...
{% for form_data in formset %}
<div class="mt-4 w-1/2 mx-1">
{{ form_data.nom_qualité }}
</div>
<div class="mt-4 w-1/2 mx-1">
{{ form_data.id_qualité }}
</div>
<div class="mt-4 w-1/2 mx-1">
{{ form_data.date_début }}
</div>
<div class="mt-4 w-1/2 mx-1">
{{ form_data.date_fin }}
</div>
{% endfor %}
<button type="button" class="btn btn-sm btn-success add-form-row"
id="{{ formset.prefix }}">
ajouter
</button>
{{ formset.management_form }}
...
</form>
<script type="text/javascript" src="{% static 'js/formset.js' %}">
</script>
js file
function updateElementIndex(el, prefix, ndx) {
var id_regex = new RegExp('(' + prefix + '-\\d+-)');
var replacement = prefix + '-' + ndx + '-';
if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex,
replacement));
if (el.id) el.id = el.id.replace(id_regex, replacement);
if (el.name) el.name = el.name.replace(id_regex, replacement);
}
function addForm(btn, prefix) {
var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
if (formCount < 1000) {
// Clone a form (without event handlers) from the first form
var row = $(".item:last").clone(false).get(0);
// Insert it after the last form
$(row).removeAttr('id').hide().insertAfter(".item:last").slideDown(300);
// Remove the bits we don't want in the new row/form
// e.g. error messages
$(".errorlist", row).remove();
$(row).children().removeClass("error");
// Relabel or rename all the relevant bits
$(row).find('.formset-field').each(function () {
updateElementIndex(this, prefix, formCount);
$(this).val('');
$(this).removeAttr('value');
$(this).prop('checked', false);
});
// Add an event handler for the delete item/form link
$(row).find(".delete").click(function () {
return deleteForm(this, prefix);
});
// Update the total form count
$("#id_" + prefix + "-TOTAL_FORMS").val(formCount + 1);
} // End if
return false;
}
function deleteForm(btn, prefix) {
var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
if (formCount > 1) {
// Delete the item/form
var goto_id = $(btn).find('input').val();
if( goto_id ){
$.ajax({
url: "/" + window.location.pathname.split("/")[1] + "/formset-data-delete/"+ goto_id +"/
next="+ window.location.pathname,
error: function () {
console.log("error");
},
success: function (data) {
$(btn).parents('.item').remove();
},
type: 'GET'
});
}else{
$(btn).parents('.item').remove();
}
var forms = $('.item'); // Get all the forms
// Update the total number of forms (1 less than before)
$('#id_' + prefix + '-TOTAL_FORMS').val(forms.length);
var i = 0;
// Go through the forms and set their indices, names and IDs
for (formCount = forms.length; i < formCount; i++) {
$(forms.get(i)).find('.formset-field').each(function () {
updateElementIndex(this, prefix, i);
});
}
} // End if
return false;
}
$("body").on('click', '.remove-form-row',function () {
deleteForm($(this), String($('.add-form-row').attr('id')));
});
$("body").on('click', '.add-form-row',function () {
return addForm($(this), String($(this).attr('id')));
});
I am trying to make a voting app using Blockchain on truffle framework. The data from the network is not rendered on the webpage.
Only loading is displayed but the actual content is not displayed even though I have connected by Blockchain accounts from Ganache to my metamask extension.
Here is my code:
Election.sol
pragma solidity ^0.5.0;
contract Election {
// Model a Candidate for first past the post system
struct Candidatepost {
uint id;
string name;
uint voteCount;
}
// Model as candidate for proportional party system
struct Candidateparty {
uint id;
string name;
uint voteCount;
}
// Store accounts that have voted
mapping(address => bool) public voters;
// Store Candidates
// Fetch Candidate
mapping(uint => Candidatepost) public cand_post;
mapping(uint => Candidateparty) public cand_party;
// Store Candidates Count
uint public partyCount;
uint public postCount;
uint[] public candidatesCount = [postCount,partyCount];
constructor () public {
addpostCandidate("Candidate 1");
addpostCandidate("Candidate 2");
addpartyCandidate("Candidate 1");
addpartyCandidate("Candidate 2");
candidatesCount = [postCount,partyCount];
}
function addpostCandidate (string memory _name) private {
postCount ++;
cand_post[postCount] = Candidatepost(postCount, _name, 0);
}
function addpartyCandidate (string memory _name) private {
partyCount ++;
cand_party[partyCount] = Candidateparty(partyCount, _name, 0);
}
// voted event
event votedEvent (
uint indexed _candidateId1,
uint indexed _candidateId2
);
function vote (uint _candidateId1, uint _candidateId2) public {
// require that they haven't voted before
require(!voters[msg.sender]);
// require a valid candidate
require(_candidateId1 > 0 && _candidateId1 <= postCount && _candidateId2 > 0 && _candidateId2 <= partyCount);
// record that voter has voted
voters[msg.sender] = true;
// update candidate vote Count
cand_post[_candidateId1].voteCount ++;
cand_party[_candidateId2].voteCount ++;
// trigger voted event
emit votedEvent(_candidateId1, _candidateId2);
}
}
App.js
App = {
web3Provider: null,
contracts: {},
account: '0x0',
init: function() {
return App.initWeb3();
},
initWeb3: function() {
// TODO: refactor conditional
if (typeof web3 !== 'undefined') {
// If a web3 instance is already provided by Meta Mask.
App.web3Provider = web3.currentProvider;
web3 = new Web3(web3.currentProvider);
} else {
// Specify default instance if no web3 instance provided
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
web3 = new Web3(App.web3Provider);
}
return App.initContract();
},
initContract: function() {
$.getJSON("Election.json", function(election) {
// Instantiate a new truffle contract from the artifact
App.contracts.Election = TruffleContract(election);
// Connect provider to interact with contract
App.contracts.Election.setProvider(App.web3Provider);
App.listenForEvents();
return App.render();
});
},
// Listen for events emitted from the contract
listenForEvents: function() {
App.contracts.Election.deployed().then(function(instance) {
// Restart Chrome if you are unable to receive this event
// This is a known issue with Metamask
// https://github.com/MetaMask/metamask-extension/issues/2393
instance.votedEvent({}, {
fromBlock: 0,
toBlock: 'latest'
}).watch(function(error, event) {
console.log("event triggered", event)
// Reload when a new vote is recorded
App.render();
});
});
},
render: function() {
var electionInstance;
var loader = $("#loader");
var content = $("#content");
loader.show();
content.hide();
// Load account data
web3.eth.getCoinbase(function(err, account) {
if (err === null) {
App.account = account;
$("#accountAddress").html("Your Account: " + account);
}
});
//load contract data
App.contracts.Election.deployed().then(function(instance) {
electionInstance = instance;
return electionInstance.candidatesCount();
}).then(function(1) {
var postcandidatesResults = $("#postcandidatesResults");
postcandidatesResults.empty();
var partycandidatesResults = $("#partycandidatesResults");
partycandidatesResults.empty();
var postcandidatesSelect = $('#postcandidatesSelect');
postcandidatesSelect.empty();
var partycandidatesSelect = $('#partycandidatesSelect');
partycandidatesSelect.empty();
for (var i = 1; i <= 2; i++) {
electionInstance.cand_post(i).then(function(candidate) {
var id = candidate[0];
var name = candidate[1];
var voteCount = candidate[2];
// Render candidate Result
var candidateTemplate = "<tr><th>" + id + "</th><td>" + name + "</td><td>" + voteCount + "</td></tr>";
postcandidatesResults.append(candidateTemplate);
// Render candidate ballot option
var candidateOption = "<option value='" + id + "' >" + name + "</ option>";
postcandidatesSelect.append(candidateOption);
});
}
for (var j = 1; j <= 2; j++) {
electionInstance.cand_party(i).then(function(candidate) {
var id2 = candidate[0];
var name2 = candidate[1];
var voteCount2 = candidate[2];
// Render candidate Result
var candidateTemplate2 = "<tr><th>" + id2 + "</th><td>" + name2 + "</td><td>" + voteCount2 + "</td></tr>";
partycandidatesResults.append(candidateTemplate2);
// Render candidate ballot option
var candidateOption2 = "<option value='" + id2 + "' >" + name2 + "</ option>";
partycandidatesSelect.append(candidateOption2);
});
}
return electionInstance.voters(App.account);
}).then(function(hasVoted) {
// Do not allow a user to vote
if(hasVoted) {
$('form').hide();
}
loader.hide();
content.show();
}).catch(function(error) {
console.warn(error);
});
},
castVote: function() {
var candidateId1 = $('#postcandidatesSelect').val();
var candidateId2 = $('#partycandidatesSelect').val();
App.contracts.Election.deployed().then(function(instance) {
return instance.vote(candidateId1, candidateId2, { from: App.account });
}).then(function(result) {
// Wait for votes to update
$("#content").hide();
$("#loader").show();
}).catch(function(err) {
console.error(err);
});
}
};
$(function() {
$(window).load(function() {
App.init();
});
});
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Election Results</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container" style="width: 650px;">
<div class="row">
<div class="col-lg-12">
<h1 class="text-center">
<div class="row d-flex justify-content-center" style="border:none;background:white;">
<div class="col-md-1 col-3">
<img class="mx-auto d-block img-fluid" src="images/logo.png" style="" alt="">
</div>
</div></h1>
<hr/>
<br/>
<h1 class="text-center">National Election-2075</h1>
<h1 class="text-center">Election Updates</h1>
<div id="loader">
<p class="text-center">Loading...</p>
</div>
<div id="content" style="display: none;">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Votes</th>
</tr>
</thead>
<tbody id="postcandidatesResults">
</tbody>
</table>
<hr/>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Votes</th>
</tr>
</thead>
<tbody id="partycandidatesResults">
</tbody>
</table>
<hr/>
<form onSubmit="App.castVote(); return false;">
<div class="form-group">
<label for="postcandidatesSelect">Select Candidate</label>
<select class="form-control" id="postcandidatesSelect">
</select>
</div>
<div class="form-group">
<label for="partycandidatesSelect">Select Candidate</label>
<select class="form-control" id="partycandidatesSelect">
</select>
</div>
<button type="submit" class="btn btn-primary">Vote</button>
<hr />
</form>
<p id="accountAddress" class="text-center"></p>
</div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<script src="js/web3.min.js"></script>
<script src="js/truffle-contract.js"></script>
<script src="js/app.js"></script>
</body>
</html>
Any call to the blockchain is async(returns a promise). You need to either handle the promise with a .then() or you can use async await. Basically anything chained after electionInstance is async. For example:
electionInstance.candidatesCount();
electionInstance.cand_party
electionInstance.voters
I'm creating an MVC page that uses Kendo validation.
I have the following Model:
public class ForgotPasswordModel
{
[Required(ErrorMessage = " ")]
public string UserName { get; set; }
[Required(ErrorMessage = " ")]
[EmailAddress(ErrorMessage = " ")]
public string Email { get; set; }
public string PhoneNumber { get; set; }
[Required(ErrorMessage = " ")]
public string Code { get; set; }
}
I do not want my view to show Error Message for the Email field. I want it to show only exclamation sign when validation fails.
Currently I have the following code in my View:
#model Site.Models.ForgotPasswordModel
#{
ViewBag.Title = "Forgot Password";
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="width=device-width" />
<title>Login</title>
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Content/kendo/kendo.common-material.min.css" rel="stylesheet" />
<link href="~/Content/kendo/kendo.custom.css" rel="stylesheet" />
<link href="~/Content/kendo/custom.css" rel="stylesheet" />
<script src="~/Scripts/kendo/kendo.all.min.js"></script>
<script src="~/Scripts/kendo/kendo.aspnetmvc.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<style>
input[type=text]::-ms-clear {
display: none;
}
input[type=password]::-ms-reveal {
display: none;
}
.errMsg {
font-weight: bolder;
color: red;
}
span#UserName_validationMessage, span#Email_validationMessage,span#Code_validationMessage {
display: inline-block;
width: 160px;
text-align: left;
border: 0;
padding: 0;
margin: -20px;
background: none;
box-shadow: none;
color: red;
}
.k-invalid-msg {
display: none;
}
</style>
</head>
<body>
<div>
</div>
<div style="margin-top: 20px;">
<div style="margin: 0 auto; width: 940px; height: 409px; background-image: url('../../Content/images/finance-globe.jpg');"/>
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "ForgotPasswordForm" }))
{
<div style="margin: 0 auto; margin-top: 20px;">
<table id="ForgotPassword" style="margin: 0" auto;">
<tr style="height:40px;">
<td>#Html.EditorFor(x => x.UserName, new { htmlAttributes = new { #class = "form-control k-textbox checkError", placeholder = "username" } })</td>
</tr>
<tr style="height:40px;">
<td>#Html.EditorFor(x => x.Email, new { htmlAttributes = new { #class = "form-control k-textbox checkError", placeholder = "email" } })</td>
</tr>
<tr style="height:40px;">
<td>#Html.EditorFor(x => x.PhoneNumber, new { htmlAttributes = new { #class = "form-control k-textbox", placeholder = "phone number" } })</td>
</tr>
<tr style="height:40px;">
<td>#Html.EditorFor(x => x.Code, new { htmlAttributes = new { #class = "form-control k-textbox checkError", placeholder = "code" } })</td>
</tr>
</table>
</div>
}
</div>
</body>
</html>
<script>
$(document).ready(function () {
$("#ForgotPasswordForm").kendoValidator();
});
</script>
The Model and View produce the following:
enter image description here
I do not want "Email is not valid" message to be displayed in case of regular expression validation fails.
I just need an exclamation sign.
How can I do that?
For your email field you can try adding data-email-msg attribute, which is way to customize the validation message for wrong email field value.
For ex: If you want to display a blank message for wrong value for email id you can do something like:
<input type="email" name="email" id="email" name="email" data-email-msg="">
And if you want to customize the required field validation message too, then you can add an another attribute data-required-msg as below:
<input type="email" name="email" id="email" name="email" data-email-msg="" data-required-msg="">
I am using an if-template to show or hide items in a list, within a Polymer-element.
My template is based on a list of values, and filtered using a reference list.
Updating the list of values yields the desired effect. However, changing the filter reference list (here removing one element) does not yield an update of the template.
<!DOCTYPE html>
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/polymer/0.2.3/platform.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/polymer/0.2.3/polymer.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<test-component></test-component>
</body>
</html>
<polymer-element name='test-component' attributes='itemlist filterlist'>
<template>
<style>
</style>
<table id='table'>
<tr template repeat="{{item in itemlist}}">
<template if="{{item | applyFilter(filterlist)}}">
<td>test</td>
</template>
</tr>
</table>
<input type='button' value='remove 1 element' on-click={{clicked}}></input>
<div id='msg'></div>
</template>
<script>
Polymer('test-component', {
itemlist: [1,2,3],
filterlist: [1,2],
applyFilter: function(item, filterlist) {
var test = false;
if (filterlist) {
filterlist.forEach(function(filteritem) {
test = test || ((new RegExp(filteritem)).test(item));
});
}
return test;
},
clicked: function() {
this.$.msg.innerHTML = 'Filter list was ' + this.filterlist;
this.filterlist.splice(1,1);
this.$.msg.innerHTML += ', now it\'s ' + this.filterlist;
}
});
See http://jsbin.com/vuvikare/4/edit?html,output for runnable code.
Is there a way to trigger this update (for example using filterChanged observer)?
Thanks
This is very much a hack, but I got it to work by adding this method:
filterlistChanged: function() {
Array.prototype.forEach.call(this.$.table.querySelectorAll('template[if]'), function(t) {
t.iterator_.updateIteratedValue();
});
},
Basically, it finds all the inner template elements in the table and forces them to update (using a private method).
I have an input field. When the user clicks it some javascript converts the text to a Raphael JS library variable. I want to put each letter into a Raphael variable called string followed by a \n. When the user clicks on the button nothing is displayed. Can someone help me fix this?...
<html>
<head>
<script src="raphael.js"></script>
<script src="jquery-1.7.2.js"></script>
<script type="text/javascript">
var string = "";
function animate() {
var txt = document.getElementById("words").value;
var splittxt = txt.split("");
var i;
for (i = 0; i < splittxt.length; i++) {
var string = splittxt[i] + "\n\n";
}
}
</script>
<style type="text/css">
#letters
{
text-align:center;
margin-left:10px;
width:25px;
float:left;
text-shadow:10px 5px 1px #4D4D4D;
filter:DropShadow(Color=#4D4D4D, OffX=10, OffY=5);
font-weight:bold;
}
</style>
</head>
<body>
Text: <input type="text" id="words" />
<input type="button" value="Animate" onclick="animate()" />
<div id='letters'></div>
<div id="draw-here-raphael" style="height: 200px; width: 400px; margin-top:0px; background-color:blue;">
</div>
<div id="elps" style="ma
rgin-left:100px;"/>
<script type="text/javascript"> //all your javascript goes here
var r = new Raphael("draw-here-raphael");
var string = r.text(50,50, string);
</script>
</body>
</html>
Instead of setting the variable string, you want add to it. Also, there were quite a few other updates I made to your excerpt...
Setting variables to reserved words can also cause a lot of problems.
http://jsfiddle.net/fN9Me/
<html>
<head>
<script src="raphael.js"></script>
<script src="jquery-1.7.2.js"></script>
<script type="text/javascript">
var alpha = "";
var something = "";
var r = "";
var txt = "";
var splittxt = "";
$(function() {
r = new Raphael("draw-here-raphael");
$("#animate").click(function() {
txt = $("#words").val();
splittxt = txt.split("");
var i;
for (i = 0; i < splittxt.length; i++) {
something += splittxt[i] + "\n\n";
}
alpha = r.text(50, 50, something);
});
});
</script>
<style type="text/css">
#letters
{
text-align:center;
margin-left:10px;
width:25px;
float:left;
text-shadow:10px 5px 1px #4D4D4D;
filter:DropShadow(Color=#4D4D4D, OffX=10, OffY=5);
font-weight:bold;
}
</style>
</head>
<body>
Text: <input type="text" id="words" value="" />
<input id="animate" type="button" value="Animate" />
<div id='letters'></div>
<div id="draw-here-raphael" style="height: 200px; width: 400px; margin-top:0px; background-color:blue;">
</div>
<div id="elps" style="margin-left:100px;"/>
</body>
</html>
Update:
To remove the previous text, it is just a matter of utilizing the Raphael remove function. Also we have to reset the variable something
if (alpha) alpha.remove();
http://jsfiddle.net/fN9Me/1/
You're not actually displaying anything. This line:
document.getElementById("letters").innerHTML + splittxt[i] + "<br>";
needs to be something like:
document.getElementById("letters").innerHTML += splittxt[i] + "<br>";
The value of the words input is blank => when you call the split method var splittxt = txt.split(""); the splittxt has a length == 0, and therefore the body of the for statement is never executed.