I am new to JSP and I want to validate an HTML form using JSP, I am using an if-else statement in my code. But it's not working properly.
<%
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String email = request.getParameter("email");
String uname = request.getParameter("username");
String pw = request.getParameter("password");
String pw1 = request.getParameter("confirm");
String phone = request.getParameter("phone");
String idno = request.getParameter("idno");
String gender = request.getParameter("gender");
String dob = request.getParameter("dob");
String bgroup = request.getParameter("bloodgroup");
String bweight = request.getParameter("weight");
String lastdonate = request.getParameter("lddate");
if (request.getParameter(fname) == null
|| request.getParameter(lname) == null
|| request.getParameter(email) == null
|| request.getParameter(uname) == null
|| request.getParameter(pw) == null
|| request.getParameter(pw1) == null
|| request.getParameter(phone) == null
|| request.getParameter(idno) == null
|| request.getParameter(dob) == null
|| request.getParameter(bweight) == null
|| request.getParameter(lastdonate) == null) {
out.println("<div class='alert-message alert-message-warning' align='center'>"+
"<h4>Alert Message Warning</h4>"+
"<p>Some Fields Are Empty <br>" +
"<strong>Please Fill All The Fields</strong>."+
"</p></div>");
}
else if (request.getParameter(pw) != request.getParameter(pw1) ) {
out.println("<div class='alert-message alert-message-warning' align='center'>"+
"<h4>Alert Message Warning</h4>"+
"<p>Confirmed Password Doesn't Match With the Password <br>" +
"<strong>Please Re-Type Your Password</strong>."+
"</p></div>");
}
else {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
System.out.println(ex);
}
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/minutehelp","root","");
Statement stm = con.createStatement();
stm.executeUpdate("INSERT INTO donors VALUES(NULL, '"+fname+"', '"+lname+"', '"+email+"', '"+uname+"', '"+pw1+"', '"+phone+"', '"+idno+"', '"+gender+"', '"+dob+"', '"+bgroup+"', '"+bweight+"', '"+lastdonate+"')");
stm.close();
} catch (Exception ex) {
out.println(ex);
}
}
%>
First I want to check whether all the fields are empty or filled, then I want to check whether the password and confirmed passwords are same and if there are no errors with these I want to send these data to my database table 'donors'. But it's not working properly and it always displays the warning message inside the if statement and data is not being inserted. But if I use only if statements instead of if-else, it always displays the first warning message and inserts data each time even if conditions were false.
I am very new to JSP, please someone help me here.
Thank you.
Problem in your if statement is that you are trying to compare i.e request.getParameter(fname) and so on . but that doesn't exist. if you want to compare put " " this in your request.getParameter("something")
Also if you want to compare using variable in your case fname,pw,pw1 etc. try doing something like this
if(fname==null || uname==null ... ){
//do something
}
Now to see if value of password are equal try doing this in your else-if
else if (pw.equals(pw1) ) {
//do something
}
Also,you can modify your code like this to achieve what you want
if(fname!=null || uname!=null ...){
if (pw.equals(pw1) ) {
//your insert code put here
}else{
out.println("<div class='alert-message alert-message-warning' align='center'>"+
"<h4>Alert Message Warning</h4>"+
"<p>Confirmed Password Doesn't Match With the Password <br>" +
"<strong>Please Re-Type Your Password</strong>."+
"</p></div>");
}
}else{
out.println("<div class='alert-message alert-message-warning' align='center'>"+
"<h4>Alert Message Warning</h4>"+
"<p>Some Fields Are Empty <br>" +
"<strong>Please Fill All The Fields</strong>."+
"</p></div>");
}
Hope this helps !!
Related
i have a signup page connected to sql database.now i want to have validations in signup page like firstname,lastname,username etc can not be empty using java how can i do that
My code is
String fname=Fname.getText();
String lname=Lname.getText();
String uname=Uname.getText();
String emailid=Emailid.getText();
String contact=Contact.getText();
String pass=String.valueOf(Pass.getPassword());
Connection conn=null;
PreparedStatement pstmt=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/zeeshan","root","sHaNi97426");
pstmt=conn.prepareStatement("Insert into signup1 values(?,?,?,?,?,?)");
pstmt.setString(1,fname);
pstmt.setString(2,lname);
pstmt.setString(3,uname);
pstmt.setString(4,emailid);
pstmt.setString(5,contact);
pstmt.setString(6,pass);
int i=pstmt.executeUpdate();
if(i>0)
{
JOptionPane.showMessageDialog(null,"Successfully Registered");
}
else
{
JOptionPane.showMessageDialog(null,"Error");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
First your question is not direct. Validation occurs before database query. You should not proceed to database Connetction or making any query.
What should you do:
public static boolean nullOrEmpty(String value) {
return value == null || value.trim().equals("") ? true : false;
}
public void yourMethod(){
try{
//YourCode Here
String fname=Fname.getText();
if(nullOrEmpty(fname)){
new throw ValidationException("First name should not be null.");
}
//YourCode Here
}catch(ValidationException e){
System.err.println("Exception:"+e.getMessage());
}
}
Check for every string to validate.
that should not be hard, you can do it with simple if and else like below
if(fname != null && fname.isEmpty()){
throw new Exception(fname+" cannot be empty");
}else if(lname != null && lname.isEmpty()){
throw new Exception(fname+" cannot be empty");
}
.....
as a recommendation you should abstract validation and database access objects . see example of MVC here
You may do it just by downloading a jar named org.apache.commons.lang
Stringutils Class Reference
Sample Code
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
or
StringUtils.isEmpty(obj_String); // Another method to check either null or "";
To check if a String is empty you can use the method .isEmpty(). You'll probably want to use .trim() first, as this removes all the whitespaces at the beginning and ending of the String. For more options check out the full documentation here.
I have a form and I put the forms data in an intent and then start a new activity and send the data with the intent, but I wanna do a check if the strings are empty I should display and error message. If the strings are not empty the activity can be started.
I've tried the following code but it doesn't seem to be working. If the field is empty it just starts the other activity
(I've tried with only 1 field for now, because I don't know how to to it for multiple fields)
//getting the field values
String firstname = editTextFirstname.getText().toString();
String lastname = editTextLastname.getText().toString();
String amount = editTextBedrag.getText().toString();
String timespan = spinnerPeriode.getSelectedItem().toString();
String iban = editTextIBAN.getText().toString();
if(firstname != null) {
//putting data in the intent
intent.putExtra(FIRSTNAME, firstname);
intent.putExtra(LASTNAME, lastname);
intent.putExtra(AMOUNT, amount);
intent.putExtra(TIMESPAN, timespan);
intent.putExtra(IBAN, iban);
startActivity(intent);
}else{
Toast.makeText(MainActivity.this, "Oops, you forgot to fill in some fields!", Toast.LENGTH_SHORT).show();
}
A cleaner way to do this is
public static boolean isAnyStringNullOrEmpty(String... strings) {
for (String s : strings)
if (s == null || s.isEmpty())
return true;
return false;
}
Then you can call it like this
if (isAnyStringNullOrEmpty(firstname, lastname, amount, timespan, iban)) {
Toast.makeText(MainActivity.this, "Oops, you forgot to fill in some fields!", Toast.LENGTH_SHORT).show();
} else {
}
Using apache commons, we can do this as:
boolean valid = StringUtils.isNoneEmpty(firstname, lastname, amount, timespan, iban)
Change
if(firstname != null)
to
if(!TextUtils.isEmpty(firstname) && !TextUtils.isEmpty(lastname) &&
!TextUtils.isEmpty(amount) &&!TextUtils.isEmpty(timespan) &&
!TextUtils.isEmpty(iban))
Java 8 + Apache Commons Lang only:
String firstname = editTextFirstname.getText().toString();
String lastname = editTextLastname.getText().toString();
String amount = editTextBedrag.getText().toString();
String timespan = spinnerPeriode.getSelectedItem().toString();
String iban = editTextIBAN.getText().toString();
boolean valid = Stream.of(firstname, lastname, amount, timespan, iban)
.allMatch(StringUtils::isNotBlank);
if(firstname != null && lastname != null && amount != null && timespan != null
&& iban != null & firstname.trim().isEmpty() && !lastname.trim().isEmpty() &&
!amount .trim().isEmpty() && !timespan.trim().isEmpty() && !iban.trim().isEmpty())
Using Java Stream API:
private boolean anyBlank(String...strings) {
return Stream.of(strings).anyMatch(string -> isBlank(string));
}
When I delete the else if part it works fine, but if I keep it, it gives me java.sql.SQLException: No data found And obviously I want my String variable get the value from database cell IF the cell wasn't emtpy.
String updatedby = ""; // Outside of While loop
// Inside the while loop.
if(rs.getString("UpdatedBy") == null)
{ updatedby = ""; }
else if(rs.getString("UpdatedBy") != null)
{ updatedby = rs.getString("UpdatedBy"); updatedby = updatedby.trim(); }
I'm confused.
Why don't you just call it once?
updatedby = rs.getString("UpdatedBy");
updatedby = (updatedby == null ? "" : updatedby.trim());
Less overhead that way. And less code. Cleaner.
You should be able to use ResultSet.wasNull() which reports whether the last column read had a value of SQL NULL. Something like
updatedBy = rs.getString("UpdatedBy");
if (!rs.wasNull()) {
updatedBy = updatedBy.trim();
} else {
updatedBy = "";
}
i am trying to have a check on that if value is null then don't show the message and recall the constructor, i did the following way but its not working.
if (title == null) {
JOptionPane.showMessageDialog(null, "Please Enter All Values");
new InfoFrame();
}
else {
try {
System.out.println(title+""+date);
System.out.println(title+""+date);
s.execute("INSERT INTO task ([title],[deadline],[priority],[time]) VALUES ('"+ title+ "','"+ date+ "','"+ priority + "','"+ time + "')");
JOptionPane.showMessageDialog(null,"Your Task has been added to the Database:");
} catch (Exception e) {
System.out.println(e.getMessage());
}
*Edited the var Title like stupid naming conventions
if (Title.isEmpty()) {
Will do the trick.
If you want to check both null or empty
if (Title == null || Title.isEmpty()) {
Also its better to start your variable in simple letters.
How can I detect when a json value is null?
for example: [{"username":null},{"username":"null"}]
The first case represents an unexisting username and the second a user named "null". But if you try to retrieve them both values result in the string "null"
JSONObject json = new JSONObject("{\"hello\":null}");
json.put("bye", JSONObject.NULL);
Log.e("LOG", json.toString());
Log.e("LOG", "hello="+json.getString("hello") + " is null? "
+ (json.getString("hello") == null));
Log.e("LOG", "bye="+json.getString("bye") + " is null? "
+ (json.getString("bye") == null));
The log output is
{"hello":"null","bye":null}
hello=null is null? false
bye=null is null? false
Try with json.isNull( "field-name" ).
Reference: http://developer.android.com/reference/org/json/JSONObject.html#isNull%28java.lang.String%29
Because JSONObject#getString returns a value if the given key exists, it is not null by definition. This is the reason JSONObject.NULL exists: to represent a null JSON value.
json.getString("hello").equals(JSONObject.NULL); // should be false
json.getString("bye").equals(JSONObject.NULL); // should be true
For android it will raise an JSONException if no such mapping exists. So you can't call this method directly.
json.getString("bye")
if you data can be empty(may not exist the key), try
json.optString("bye","callback string");
or
json.optString("bye");
instead.
In your demo code, the
JSONObject json = new JSONObject("{\"hello\":null}");
json.getString("hello");
this you get is String "null" not null.
your shoud use
if(json.isNull("hello")) {
helloStr = null;
} else {
helloStr = json.getString("hello");
}
first check with isNull()....if cant work then try belows
and also you have JSONObject.NULL to check null value...
if ((resultObject.has("username")
&& null != resultObject.getString("username")
&& resultObject.getString("username").trim().length() != 0)
{
//not null
}
and in your case also check resultObject.getString("username").trim().eqauls("null")
If you must parse json first and handle object later, let try this
Parser
Object data = json.get("username");
Handler
if (data instanceof Integer || data instanceof Double || data instanceof Long) {
// handle number ;
} else if (data instanceof String) {
// hanle string;
} else if (data == JSONObject.NULL) {
// hanle null;
}
Here's a helper method I use so that I can get JSON strings with only one line of code:
public String getJsonString(JSONObject jso, String field) {
if(jso.isNull(field))
return null;
else
try {
return jso.getString(field);
}
catch(Exception ex) {
LogHelper.e("model", "Error parsing value");
return null;
}
}
and then something like this:
String mFirstName = getJsonString(jsonObject, "first_name");
would give you your string value or safely set your string variable to null. I use Gson whenever I can to avoid pitfalls like these. It handles null values much better in my opinion.