Validate a numeric value range from html form textbox. PHP or Javascript -
i have form contains number of textboxes i.e. volome, gain, treble, middle , bass. whole numbers can entered, validated javascript , maxlength set to, no problem there. how make sure numbers between 0 , 65535 entered.
<?php $name = $_post['ampmod']; $volume = 'volume = '. $_post['volume']; $gain = 'gain = '. $_post['gain']; $treble = 'treble = '. $_post['treble']; $middle = 'middle = '. $_post['middle']; $bass = 'bass = '. $_post['bass']; if($volume != null && $gain != null && $treble != null && $middle != null && $bass != null) { echo "<h3> $name </h3>"; echo "<table><tr>"; echo "<td>$volume</td>"; echo "<td>$gain</td>"; echo "<td>$treble</td>"; echo "<td>$middle</td>"; echo "<td>$bass</td>"; } else {echo ("please try again. values must between 0-65535. 0=off 65535=full on 10<br><a href = \"ampchoice.php\">click here try again!</a>");} ?>
it important mention $volume, $gain, $treble, $middle , $bass never null have assigned string them in addition $_post value. in addition should check if $_post values exist before trying use them (or undefined notice message).
here example php version based on code had (untested, should work fine).
<?php function isvalidrange( $value, $low = 0, $high = 65535) { // validate / cast value int (add additional validation here $value = (int)$value; if ( $value > $high || $value < $low ) { // return null (not valid value) return null; } // otherwise value valid return return $value; } // make sure $name var safe use $name = ( isset($_post['ampmod']) ) ? htmlentities($_post['ampmod'],ent_quotes,'utf-8') : null; $volume = ( isset($_post['volume']) ) ? isvalidrange($_post['volume']) : null; $gain = ( isset($_post['gain']) ) ? isvalidrange($_post['gain']) : null; $treble = ( isset($_post['treble']) ) ? isvalidrange($_post['treble']) : null; $middle = ( isset($_post['middle']) ) ? isvalidrange($_post['middle']) : null; $bass = ( isset($_post['bass']) ) ? isvalidrange($_post['bass']) : null; if( isset($volume) && isset($gain) && isset($treble) && isset($middle) && isset($bass) ) { echo "<h3> $name </h3>"; echo "<table><tr>"; echo "<td>volume = $volume</td>"; echo "<td>gain = $gain</td>"; echo "<td>treble = $treble</td>"; echo "<td>middle = $middle</td>"; echo "<td>bass = $bass</td>"; echo "</tr></table>"; } else { echo ("please try again. values must between 0-65535. 0=off 65535=full on 10<br><a href = \"ampchoice.php\">click here try again!</a>");} ?>
lastly not recommend relying on javascript check if values safe use (i.e. echo them out), using js pre-warning users , validating php best way go.
Comments
Post a Comment