null pointer exception from DispatchAction - list

I am trying to insert records into MySQL from UI but I am getting nullpointerexception in JSP page. Below are my files.
Struts File
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<action-mappings>
<action
path="/inputemployee"
forward="/pages/inputemployee.jsp"/>
<action path="/db" parameter="method" type="com.pramesh.strutsdatabase.action.DataBaseAction">
<forward name="success" path="/pages/insertsucess.jsp"/>
</action>
</action-mappings>
</struts-config>
inputemployee.jsp file
<%#taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<script >
function calculate(){
document.frm.action="db.html";
var selection=document.frm.sel.selectedIndex
if(selection==1){
document.frm.method.value="insert";
}
document.frm.submit();
}
</script>
<body>
<form name ="frm">
Enter Employee ID :<input name ="Employee ID"/>
Enter Employee First Name :<input name ="First Name"/>
Enter Employee Last Name :<input name ="Last Name"/>
<select name ="sel">
<option>Please Select</option>
<option value="1">Insert</option>
</select>
<input name ="method" type ="hidden" />
<input type ="button" value="Insert" onClick="calculate()"/>
</form>
</body>
</html>
Employee.java
package com.sigma.pojo;
import org.apache.struts.action.ActionForm;
public class Employee {
private int empId;
private String firstName;
private String lastName;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override
public String toString() {
return "Employee [empId=" + empId + ", firstName=" + firstName
+ ", lastName=" + lastName + "]";
}
}
EmployeeDAO.java
package com.sigma.employeedDAO;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.sigma.pojo.Employee;
public class EmployeeDAO {
private Connection con = null;
private java.sql.Statement stmt = null;
private java.sql.PreparedStatement pstmt = null;
private ResultSet rs = null;
private Employee e;
private List <Employee> list= null;
private Connection getConnection(){
if (con==null){
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "kalokando11");
} catch (ClassNotFoundException | SQLException e) {}
}
return con;
}
public List<Employee> getEmployee(){
list = new ArrayList<Employee>();
try {
stmt = getConnection().createStatement();
rs = stmt.executeQuery("select * from employee");
while(rs.next()){
frm = new Employee();
frm.setEmpId(rs.getInt("emp_id"));
frm.setFirstName(rs.getString("first_name"));
frm.setLastName(rs.getString("last_name"));
list.add(frm);
}
} catch (SQLException e1) {
}
close();
return list;
}
public void insert(Employee e1) throws SQLException{
pstmt = getConnection().prepareStatement("Insert into employee values (?,?,?) ");
pstmt.setInt(1,e1.getEmpId());
pstmt.setString(2, e1.getFirstName());
pstmt.setString(3,e1.getLastName());
pstmt.execute();
close();
}
public void close(){
try {
con.close();
stmt.close();
pstmt.close();
rs.close();
} catch (SQLException e) {
}
}
}
DataBaseAction.java
package com.pramesh.strutsdatabase.action;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import com.sigma.employeedDAO.EmployeeDAO;
import com.sigma.pojo.Employee;
public class DataBaseAction extends DispatchAction{
public ActionForward display(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
response.setContentType("text/html");
list =dao.getEmployee();
request.setAttribute("employee", list);
return mapping.findForward("success");
}
public ActionForward insert(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
Employee e1 = new Employee();
response.setContentType("text/html");
e1.setEmpId(Integer.parseInt(request.getParameter("Employee ID")));
e1.setFirstName(request.getParameter("First Name"));
e1.setLastName(request.getParameter("Last Name"));
EmployeeDAO dao = new EmployeeDAO();
dao.insert(e1);
return mapping.findForward("success");
}
}
insertsucess.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Employee Added
</body>
</html>
listemployee.jsp
<%#page import="java.util.List"%>
<%#page import="com.sigma.pojo.Employee"%>
<%#page import="com.pramesh.strutsdatabase.action.DataBaseAction"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<body>
<table border=1>
<thead>
<tr>
<th>Employee ID</th>
<th>First Name</th>
<th>Last Name</th>
<th colspan=2>Action</th>
</tr>
</thead>
<tbody>
<c:forEach items="${employee}" var="user">
<tr>
<td><c:out value="${user.empId}" /></td>
<td><c:out value="${user.firstName}" /></td>
<td><c:out value="${user.lastName}" /></td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
Somehow I am getting NullPointerException when I call EmployeeDAO insert method. Can someone explain why? I can connect to database and update the table but I cannot display insertsucess page due to NullPointerExection.

Related

Button Click Not Working after Server.Transfer() method

Question: How Come the Button Click on the aspx page that was transferred to does not fire correctly, after the first aspx page transferred focus to it using the Server.Transfer() method in C#.
The Answer: When the button is clicked in the transferred page after the Server.Transfer, it runs the page_load() in the transferred page instead of the button_click(). If the button is clicked a second time in the transferred page, then the button_click() fires.
---- Main.aspx ----
<%# Page Language="C#" AutoEventWireup="true"
CodeBehind="Main.aspx.cs"
Inherits="Server_Transfer_App.Main" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server"
Text="Enter Your First Name: "></asp:Label>
<asp:TextBox ID="TextBox1"
runat="server"></asp:TextBox>
</div>
<p>
<asp:Button runat="server" Text="Button"
OnClick="Button1_Click" />
</p>
</form>
</body>
</html>
-----------Main.aspx.cs-----------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Server_Transfer_App
{
public partial class Main : System.Web.UI.Page
{
protected void Page_Load(object sender,
EventArgs e)
{
}
protected void Button1_Click(object sender,
EventArgs e)
{
Server.Transfer("~/WebForm1.aspx",
true);
//Response.Redirect("~/WebForm1.aspx");
}
}
}
----------- WebForm1.aspx -------
<%# Page Language="C#" AutoEventWireup="true"
CodeBehind="WebForm1.aspx.cs"
Inherits="Server_Transfer_App.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server"
Text="Label"></asp:Label>
</div>
<div>
</div>
<div>
<%--<input id="Button1" type="button" value="button 1" runat="server" onserverclick="Button1_Click"/></div>--%>
<asp:Button ID="Button1" runat="server" Text="Button 1" OnClick="Button1_Click1" />
<div>
-----------</div>
<div>
<asp:Button ID="Button2" runat="server" Text="Button 2" OnClick="Button2_Click" />
</div>
</form>
</body>
</html>
-------- WebForm1.aspx.cs ------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Server_Transfer_App
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Use when transfer to this page using Server.Transfer("~/WebForm1.aspx") from Main.aspx
Page pPage = Page.PreviousPage;
if (pPage != null)
{
Label1.Text = ((TextBox)pPage.FindControl("TextBox1")).Text;
}
else
{
//Label1.Text = "Got to here, now click Button 2 to go back.";
Label1.Text = "Did Page Load () in WebForm1, and pPage is NULL.";
}
//Response.Redirect("~/WebForm1.aspx");
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("~/Main.aspx");
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Click on Button2";
}
protected void Button1_Click1(object sender, EventArgs e)
{
Label1.Text = "Performed Button1_Click1().";
}
}
}

Data is not displayed on the browser from the blockchain server on solidity

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

MVC - What can I do if I do not want my Email field display error when regular expression validation fails?

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="">

RegEx passes but fails on browsers

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]+$/;

Return a single string value from a WebMethod in C#

I want to return just messageID but it doesn't work correctly. How can I return a single string value?
[WebMethod]
public string messageComeGetID(string from, string to)
{
try
{
sqlConn.Open();
}
catch (Exception e)
{
return null;
}
// select messageID from tblMessage where [from] = '2' AND [to] = '4' gibi.
SqlCommand cmd3 = new SqlCommand("select messageID from tblMessage where [from]=#from AND [to]=#to", sqlConn);
cmd3.Parameters.AddWithValue("#from", from);
cmd3.Parameters.AddWithValue("#to", to);
cmd3.Connection = sqlConn;
object value = cmd3.ExecuteScalar();
string messageID = Convert.ToString(value);
cmd3.ExecuteNonQuery();
cmd3.Dispose();
sqlConn.Close();
return messageID;
}
I can be implemented like this
WebService1.asmx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;
namespace StackOverflow_Solve.Services
{
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetMessage() // Home.CS
{
//return "GOGO";
Context.Response.Output.Write("Hello World");
Context.Response.End();
return string.Empty;
}
}
}
full implementation is
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<head> //HTML and Ajax
<title></title>
<script>
function GetMessage() {
//Load jQuery($) to Use
$(function() {
$.get("WebService1.asmx/GetMessage", function (data) {
console.log(data);
$("p").html(data);
});
});
}
</script>
</head>
<body>
<input type="button" onclick="GetMessage()" value="Get Message" />
<p></p>
</body>
</body>
</html>