且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用trim()删除空格,但仍未得到预期的输出

更新时间:2023-12-03 19:38:10

我建议在服务器端修剪。

在服务器端验证总是更好,因为我们可以为不同的UI应用程序使用相同的服务代码。请求可能包含错误或篡改的数据。

  String regNo = searchParamDTO.getRegNO()。trim(); 
if(regNo!= null&&!。equals(regNo)&&!null.equals(regNo)){
query + =AND UR.REG_UNIQUE_ID = :REG_UNIQUE_ID;
param.addValue(REG_UNIQUE_ID,regNo);
}


Ok,i am developing spring MVC based web application, application shows data is list, and i also facilitate filter options to enhanced search functionality, I also remove extra space by using trim(), but what happening now, when user input data in text field and enter the corresponding result will be displayed into the list, but if space added after input, the result will be "NOT FOUND" even i handle the space in javascript too

Java Code which fetches data from database

 if (searchParamDTO.getRegNO().trim() != null && !searchParamDTO.getRegNO().trim().equals("") && !searchParamDTO.getRegNO().trim().equals("null")) {
                    query += " AND UR.REG_UNIQUE_ID = :REG_UNIQUE_ID ";
                    param.addValue("REG_UNIQUE_ID", searchParamDTO.getRegNO());
                }

JavaScript Code: fetches the value in behalf of id

function setSearchParameters() {
    regNo = $('#regNo').val().trim();}

i also attached two screenshot with spaces and without spaces

Without space With space

I would suggest to trim on server side as well.
It is always better to validate on server side as we can use same serve code for different UI applications And request could be with wrong or tampered data.

 String regNo = searchParamDTO.getRegNO().trim();
 if (regNo != null && !"".equals(regNo) && !"null".equals(regNo)) {
                    query += " AND UR.REG_UNIQUE_ID = :REG_UNIQUE_ID ";
                    param.addValue("REG_UNIQUE_ID", regNo);
                }