日期:2014-05-19 浏览次数:20662 次
// java example to validate required fields public class validator { ... public static boolean validaterequired(string value) { boolean isfieldvalid = false; if (value != null && value.trim().length() > 0) { isfieldvalid = true; } return isfieldvalid; } ... } ... string fieldvalue = request.getparameter("fieldname"); if (validator.validaterequired(f ieldvalue)) { // fieldvalue is valid, continue processing request ... }
// java example to validate that a f ield is an int number public class validator { ... public static boolean validateint(string value) { boolean isfieldvalid = false; try { integer.parseint(value); isfieldvalid = true; } catch (exception e) { isfieldvalid = false; } return isfieldvalid; } ... } ... // check if the http request parameter is of type int string f ieldvalue = request.getparameter("f ieldname"); if (validator.validateint(f ieldvalue)) { // f ieldvalue is valid, continue processing request ... }
// example to convert the http request parameter to a primitive wrapper data type // and store this value in a request attribute for further processing string f ieldvalue = request.getparameter("f ieldname"); if (validator.validateint(f ieldvalue)) { // convert f ieldvalue to an integer integer integervalue = integer.getinteger(f ieldvalue); // store integervalue in a request attribute request.setattribute("f ieldname", integervalue); } ... / / use the request attribute for further processing integer integervalue = (integer)request.getattribute("f ieldname"); ...
// example to validate the f ield length public class validator { ... public static boolean validatelength(string value, int minlength, int maxlength) { string validatedvalue = value; if (!validaterequired(value)) { validatedvalue = ""; } return (validatedvalue.length() >= minlength && validatedvalue.length() <= maxlength); } ... } ... string username = request.getparameter("username"); if (validator.validaterequired(username)) { if (validator.validatelength(username, 8, 20)) { / / username is valid, continue further processing ... } }
/ / example to validate the f ield range public class validator { ... public static boolean validaterange(int value, int min, int max) { return (value >= min && value <= max); } ... } ... string f ieldvalue = request.getparameter("numberofchoic