sign-up form validations in java - java

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.

Related

My JSP if-else statement is not working properly

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 !!

null string test is always true

I already saw a lot of similar posts, but none seems to be the same as this. I am testing if a string is null in my Java Android (2.2) app and whatever the string is, it is always true. Here is the code :
public static String getLocalBluetoothName(){
String name;
if(mBluetoothAdapter == null){
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
try{
name = mBluetoothAdapter.getName();
if(name == null){
System.out.println("Name is null!");
name = mBluetoothAdapter.getAddress();
}
return name;
}
catch (Exception e){
return "";
}
}
The if(name == null) is always true even if my string has a value. By the way, I also tried mBluetoothAdapter.getName() == null and it is always true too. I saw somewhere that you can do something like that:
if(name.equals("null")){
}
But if the string is null, wouldn't that create an exception because I should not be able to use a method if the object is null? Also, testing "null" is somewhat strange to me...
Try this simplified version :
public static String getLocalBluetoothName(){
String name = null;
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter == null) {
//System.out.println("Can't get adapter");
Log.d(TAG, "Can't get adapter");
return name;
}
if ((name = adapter.getName()) == null) {
//System.out.println("Name is null!");
Log.d(TAG, "Name is null!");
name = adapter.getAddress();
}
return name;
}
and don't forget to include android.permission.BLUETOOTH permission in your app's manifest.
Also, note that sometimes your debugger may trick you by showing executing specific branches that are not in fact run (happened to me debugging in Eclipse before). So, make sure that you ACTUALLY have Name is null output in logcat, otherwise your name may be not null.
name = mBluetoothAdapter.getName();
Since name is null, your Bluetooth adapter probably doesn't have a name.
According to me, mBluetoothAdapter.getName() is always returning null, that is why the if condition is always returning true. Your method of comparing if(name == null) is absolutely correct, no doubt in this.

How to test if a JSONObject is null or doesn't exist

I have a set of JSONObject values which i receive from a server and operate on. Most times I get a JSONObject with a value (let's say statistics) and sometimes, it returns an Error object with a code and a description of the error.
How do I structure my code so that it doesn't break if it returns the error. I thought I could do this, but doesn't work.
public void processResult(JSONObject result) {
try {
if(result.getJSONObject(ERROR) != null ){
JSONObject error = result.getJSONObject(ERROR);
String error_detail = error.getString(DESCRIPTION);
if(!error_detail.equals(null)) {
//show error login here
}
finish();
}
else {
JSONObject info = result.getJSONObject(STATISTICS);
String stats = info.getString("production Stats"));
}
}
}
Use .has(String) and .isNull(String)
A conservative usage could be;
if (record.has("my_object_name") && !record.isNull("my_object_name")) {
// Do something with object.
}
It might be little late(it is for sure) but posting it for future readers
You can use JSONObject optJSONObject (String name) which will not throw any exception and
Returns the value mapped by name if it exists and is a JSONObject, or null otherwise.
so you can do
JSONObject obj = null;
if( (obj = result.optJSONObject("ERROR"))!=null ){
// it's an error , now you can fetch the error object values from obj
}
or if you just want to test nullity without fetching the value then
if( result.optJSONObject("ERROR")!=null ){
// error object found
}
There is whole family of opt functions which either return null or you can also use the overloaded version to make them return any pre-defined values.
e.g
String optString (String name, String fallback)
Returns the value mapped by name if it exists, coercing it if
necessary, or fallback if no such mapping exists.
where coercing mean, it will try to convert the value into String type
A modified version of the #TheMonkeyMan answer to eliminate redundant look-ups
public void processResult(JSONObject result) {
JSONObject obj = null;
if( (obj = result.optJSONObject("ERROR"))!=null ){
//^^^^ either assign null or jsonobject to obj
// if not null then found error object , execute if body
String error_detail = obj.optString("DESCRIPTION","Something went wrong");
//either show error message from server or default string as "Something went wrong"
finish(); // kill the current activity
}
else if( (obj = result.optJSONObject("STATISTICS"))!=null ){
String stats = obj.optString("Production Stats");
//Do something
}
else
{
throw new Exception("Could not parse JSON Object!");
}
}
In JSONObject there is a 'Has' method that you can do to Determaine the key.
I have no idea if this will work but it looks Credible.
public void processResult(JSONObject result) {
if(result.has("ERROR"))
{
JSONObject error = result.getJSONObject("ERROR")
String error_detail = error.getString("DESCRIPTION");
if(error_detail != null)
{
//Show Error Login
finish();
}
}
else if(result.has("STATISTICS"))
{
JSONObject info = result.getJSONObject("STATISTICS");
String stats = info.getString("Production Stats");
//Do something
}
else
{
throw new Exception("Could not parse JSON Object!");
}
}
It is sometimes more convenient and less ambiguous to have a NULL object than to use Java's null value.
JSONObject.NULL.equals(null) returns true.
JSONObject.NULL.toString()returns "null".
Example:
System.out.println(test.get("address").equals(null)); // Preferred way
System.out.println(test.getString("address").equals("null"));
source -- JSONObject oracle docs
Just a note:
With EE8 json specs, I can do an exception-safe get:
result.asJsonObject().getString("ERROR", null);
if, however, I want to do a check I can do it with:
result.asJsonObject().get("ERROR").equals(JsonValue.NULL)
If at any point in your code, org.json.JSONObject json_object becomes null and you wish to avoid NullPointerException (java.lang.NullPointerException), then do check it as below:
if(json_object == null) {
System.out.println("json_object is found as null");
}
else {
System.out.println("json_object is found as not null");
}
If in any case, your jsonobject is null.
Then use this statement for checking jsonobject is null or not.
if (!obj.get("data").isJsonNull()){
//Not Null
}else{
//Null
}
And for checking jsonobject is exist or not, use .has:
if (!obj.has("data")){
//Not Exist
}else{
//Exist
}

Android Json and null values

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.

XML parsing with attributes that is empty (Android)

i have an xml file with attributes like this:
<folder name = 'somename' description = ''/>
i want to display the description attribute as 'null' but it force closes and throws a FATAL Exception main in the LogCat.
i have this code below at the startElement() method
if (localName.equalsIgnoreCase("folder")) {
/** Get attribute value */
if(attributes.getValue("description")== "null"){
parseList.setFolderdesc(null);
}else{
String desc = attributes.getValue("description");
parseList.setFolderdesc(desc);
}
i tried this code but no luck...
how will i solve this without changing my xml file?
try with the following code
String desc = null;
try{
desc = attributes.getValue("description");
if((desc == null) || (desc.length()<=0)){
desc = null;
}
}catch(Exception ex){
desc = null;
}
if(parseList != null){
parseList.setFolderdesc(desc);
}
This code doesn't do what you expect:
if (attributes.getValue("description") == "null") {
You are comparing the attribute value with the String "null" not with a java null. (And you are testing strings the unsafe way too! Strings should be tested for equality using String.equals() not the == operator.)
That test should be written as follows:
if (attributes.getValue("description") == null) {
or better still:
if (attributes.getValue("description") == null ||
attributes.getValue("description").isEmpty()) {
(I'm not sure whether this will fix you problem, because I don't understand your problem description.)

Categories

Resources