权限没有,则隐藏 function forum_list_access_filter($forumlist, $gid, $allow = 'allowread') { global $grouplist; if (empty($forumlist)) return array(); if (1 == $gid) return $forumlist; $forumlist_filter = $forumlist; $group = $grouplist[$gid]; foreach ($forumlist_filter as $fid => $forum) { if (empty($forum['accesson']) && empty($group[$allow]) || !empty($forum['accesson']) && empty($forum['accesslist'][$gid][$allow])) { unset($forumlist_filter[$fid]); } unset($forumlist_filter[$fid]['accesslist']); } return $forumlist_filter; } function forum_filter_moduid($moduids) { $moduids = trim($moduids); if (empty($moduids)) return ''; $arr = explode(',', $moduids); $r = array(); foreach ($arr as $_uid) { $_uid = intval($_uid); $_user = user_read($_uid); if (empty($_user)) continue; if ($_user['gid'] > 4) continue; $r[] = $_uid; } return implode(',', $r); } function forum_safe_info($forum) { //unset($forum['moduids']); return $forum; } function forum_filter($forumlist) { foreach ($forumlist as &$val) { unset($val['brief'], $val['announcement'], $val['seo_title'], $val['seo_keywords'], $val['create_date_fmt'], $val['icon_url'], $val['modlist']); } return $forumlist; } function forum_format_url($forum) { global $conf; if (0 == $forum['category']) { // 列表URL $url = url('list-' . $forum['fid'], '', FALSE); } elseif (1 == $forum['category']) { // 频道 $url = url('category-' . $forum['fid'], '', FALSE); } elseif (2 == $forum['category']) { // 单页 $url = url('read-' . trim($forum['brief']), '', FALSE); } if ($conf['url_rewrite_on'] > 1 && $forum['well_alias']) { if (0 == $forum['category'] || 1 == $forum['category']) { $url = url($forum['well_alias'], '', FALSE); } elseif (2 == $forum['category']) { // 单页 $url = ($forum['threads'] && $forum['brief']) ? url($forum['well_alias'] . '-' . trim($forum['brief']), '', FALSE) : url($forum['well_alias'], '', FALSE); } } return $url; } function well_forum_alias() { $forumlist = forum_list_cache(); if (empty($forumlist)) return ''; $key = 'forum-alias'; static $cache = array(); if (isset($cache[$key])) return $cache[$key]; $cache[$key] = array(); foreach ($forumlist as $val) { if ($val['well_alias']) $cache[$key][$val['fid']] = $val['well_alias']; } return array_flip($cache[$key]); } function well_forum_alias_cache() { global $conf; $key = 'forum-alias-cache'; static $cache = array(); // 用静态变量只能在当前 request 生命周期缓存,跨进程需要再加一层缓存:redis/memcached/xcache/apc if (isset($cache[$key])) return $cache[$key]; if ('mysql' == $conf['cache']['type']) { $arr = well_forum_alias(); } else { $arr = cache_get($key); if (NULL === $arr) { $arr = well_forum_alias(); !empty($arr) AND cache_set($key, $arr); } } $cache[$key] = empty($arr) ? '' : $arr; return $cache[$key]; } ?>java - JSP form validation for numbers, dates and values - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - JSP form validation for numbers, dates and values - Stack Overflow

programmeradmin8浏览0评论

Hello i have a JSP page that contain a form, i want to validate the form data like date of birth format and value, breed id - zoo id that are numbers only and animals name that exist

here is my JSP page:

<%@taglib prefix="c" uri="" %> 
<%@ page import="java.util.ArrayList" %>
<%@page import="content.*"%>
<%@ page language="java" 
         contentType="text/html; charset=windows-1256"
         pageEncoding="windows-1256" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
".dtd">
<html>
<head>



<meta http-equiv="Content-Type" content="text/html; charset=windows-1256">
<title>Append Animal</title>
<link rel="stylesheet"
      href="./css/styles.css"
      type="text/css"/>
</head>
<body>
<table class="title">
  <tr><th>Zoo keeper</th></tr>
</table>


<h1>Append Animal</h1>

<form name="insert" action="Relay" >
<fieldset>
Animal new name: <input type= "text" name = "aname"><br>
Animal new DOB: <input type= "text" name = "dob"><br>


Animal new gender: 
<select name="gender" id="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<br>
Animal status: 
<select name="source" id="source">
<option value="born">Born</option>
<option value="bought">Bought</option>
</select>
<br>
Animal old zoo: <input type= "text" name = "zooid" > only if bought<br>
Animal new Breed: <input type= "text" name = "breedid" ><br>
Animal new remarks: <textarea name = "remark" rows="4" cols="20">

</textarea> <br /> <br/>


<input type="submit" value="submit">

<input type="hidden" name="mand" value="AppendAnimalServlet" > 

</fieldset>
</form>
</body></html>

i added this script in JSP page:

<script>
function validateForm()
{
    if(document.insert.aname.value ==="")
    {
      alert("Animal should have a name");
      document.insert.aname.focus();
      return false;
    }
    if(document.insert.zooid.value !=="")
    {
        if (! (/^\d*(?:\.\d{0,2})?$/.test(document.insert.zooid.value))) { 
            alert("Please enter a valid Zoo id"); 
            document.insert.zooid.focus(); 
            return false; 
        } 

      } 
    if(document.insert.breedid.value !=="")
    {
        if (! (/^\d*(?:\.\d{0,2})?$/.test(document.insert.breedid.value))) { 
            alert("Please enter a valid Breed id"); 
            document.insert.breedid.focus(); 
            return false; 
        } 

      } 
    if(document.insert.dob.value ==="")
    {
      alert("Animal should have a date of birth");
      document.insert.aname.focus();
      return false;
    }

}
</script>

but i don't think i'm doing this right any suggestion on how to deal with this ?

and please note that the form values will be transfared to a Relay servlet to handle the insert process

<form name="insert" action="Relay" onsubmit="return validateForm();">

Hello i have a JSP page that contain a form, i want to validate the form data like date of birth format and value, breed id - zoo id that are numbers only and animals name that exist

here is my JSP page:

<%@taglib prefix="c" uri="http://java.sun./jsp/jstl/core" %> 
<%@ page import="java.util.ArrayList" %>
<%@page import="content.*"%>
<%@ page language="java" 
         contentType="text/html; charset=windows-1256"
         pageEncoding="windows-1256" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3/TR/html4/loose.dtd">
<html>
<head>



<meta http-equiv="Content-Type" content="text/html; charset=windows-1256">
<title>Append Animal</title>
<link rel="stylesheet"
      href="./css/styles.css"
      type="text/css"/>
</head>
<body>
<table class="title">
  <tr><th>Zoo keeper</th></tr>
</table>


<h1>Append Animal</h1>

<form name="insert" action="Relay" >
<fieldset>
Animal new name: <input type= "text" name = "aname"><br>
Animal new DOB: <input type= "text" name = "dob"><br>


Animal new gender: 
<select name="gender" id="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<br>
Animal status: 
<select name="source" id="source">
<option value="born">Born</option>
<option value="bought">Bought</option>
</select>
<br>
Animal old zoo: <input type= "text" name = "zooid" > only if bought<br>
Animal new Breed: <input type= "text" name = "breedid" ><br>
Animal new remarks: <textarea name = "remark" rows="4" cols="20">

</textarea> <br /> <br/>


<input type="submit" value="submit">

<input type="hidden" name="mand" value="AppendAnimalServlet" > 

</fieldset>
</form>
</body></html>

i added this script in JSP page:

<script>
function validateForm()
{
    if(document.insert.aname.value ==="")
    {
      alert("Animal should have a name");
      document.insert.aname.focus();
      return false;
    }
    if(document.insert.zooid.value !=="")
    {
        if (! (/^\d*(?:\.\d{0,2})?$/.test(document.insert.zooid.value))) { 
            alert("Please enter a valid Zoo id"); 
            document.insert.zooid.focus(); 
            return false; 
        } 

      } 
    if(document.insert.breedid.value !=="")
    {
        if (! (/^\d*(?:\.\d{0,2})?$/.test(document.insert.breedid.value))) { 
            alert("Please enter a valid Breed id"); 
            document.insert.breedid.focus(); 
            return false; 
        } 

      } 
    if(document.insert.dob.value ==="")
    {
      alert("Animal should have a date of birth");
      document.insert.aname.focus();
      return false;
    }

}
</script>

but i don't think i'm doing this right any suggestion on how to deal with this ?

and please note that the form values will be transfared to a Relay servlet to handle the insert process

<form name="insert" action="Relay" onsubmit="return validateForm();">
Share Improve this question edited Nov 8, 2011 at 5:54 RobG 148k32 gold badges179 silver badges214 bronze badges asked Nov 8, 2011 at 5:29 user1031152user1031152 2394 gold badges10 silver badges15 bronze badges 5
  • You need to add a sumbit listener to the form, e.g. <form onsubmit="return validateForm();" ...> and return false from the function if validation fails to stop submission. Also note that client side validation is just a convenience for users and totally unreliable, you must still validate on the server. – RobG Commented Nov 8, 2011 at 5:35
  • when i add it to the form i get this error: Cannot return from outside a function or method. – user1031152 Commented Nov 8, 2011 at 5:38
  • When do you get the error? When you click the submit button? – RobG Commented Nov 8, 2011 at 5:45
  • when i click on submit everything works but this error i'm talking about exist in eclipse page and it's underlined with red colored line, and another thing i want to create something to check for the date i'm checking only if it's not null do you know to check date ? – user1031152 Commented Nov 8, 2011 at 5:47
  • Then it is an Eclipse issue, not a javascript issue. Add an "eclipse" tag to your question. As for validating dates, I'm sure there's a million posts here that about. You can use a simple regular expression to check format, or go a bit further and check that it's actually a valid date. Both methods are only a few lines of code. – RobG Commented Nov 8, 2011 at 5:53
Add a ment  | 

2 Answers 2

Reset to default 2

if it's not a homework, save yourself some time and use JQuery Validator:

rules: {    
    dob: {
       required: true,
       date: true },    
    firstname: "required",
    breedid: "required"
}

A validation library can be built using some generic code like the following (just a quick example, it can be extended greatly):

function validate(form) {
  var fnMap = {

    'validate-dateISO8601': {
      checkFn: isValidISO8601,
      checkMsg: 'Date must be in format yyyy-mm-dd'
    },

    'validate-dateValid': {
      checkFn: isValidDate,
      checkMsg: 'Date must be a valid date'
    }
  };

  var reClass = /(^|\s*)validate-[^\s]*/g;
  var control, controls = form.elements;
  var check, checks;
  var fn, value;

  for (var i=0, iLen=controls.length; i<iLen; i++) {
    control = controls[i];

    // Need a function here to handle more control types
    value = control.value;
    checks = control.className.match(reClass);

    // If there are any validate- classes
    if (checks) {

      // For each validate class
      for (var j=0, jLen=checks.length; j<jLen; j++) {
        check = checks[j].replace(/\s/g,'');

        // See if there is a related function
        if (fnMap.hasOwnProperty(check)) {
          check = fnMap[check];

          // If there is, run it
          // If it fails, show the message
          // This part could be collected in an array and all the
          // error messages desplayed at once or in suitable message
          // elements in the document. But alert is cheap :-)
          if (!check.checkFn(value)) {
            alert(check.checkMsg);
            control.focus();
            return false;
          }
        }
      }
    }
  }
}

// Just checks the pattern is yyyy/mm/dd
function isValidISO8601(s) {
    s.replace(/^\s+|\s+$/g, '');
    return /\d{4}[-\/]\d{2}[-\/]\d{2}/.test(s);
} 

// Checks that s is a valid date
function isValidDate(s) {
    var bits = s.split(/[-\/]/g);
    var d = new Date(bits[0], bits[1] - 1, bits[2]);
    return d.getFullYear() == bits[0] && d.getDate() == bits[2];
}

</script>

And some HTML

<form onsubmit="return validate(this);">
  <input type="text" name="foo" class="validate-dateISO8601 validate-dateValid" value="2011-02-28">
  <input type="submit">
</form>
发布评论

评论列表(0)

  1. 暂无评论