开发者

Form Validation using Javascript inside PHP

开发者 https://www.devze.com 2022-12-24 14:12 出处:网络
I have a simple problem but no matter what I try I can\'t see to get it to work. I have a form on a php page and I need to validate the qty value on my form so that it doesn\'t exceed $qty (value pull

I have a simple problem but no matter what I try I can't see to get it to work. I have a form on a php page and I need to validate the qty value on my form so that it doesn't exceed $qty (value pulled from mySQL) and is not less than zero. Sounds easy--hmm wish it were..lol! I had it checking if the value was numeric and in my attempts to make this work I even broke that--not a good morning..lol!

Here's a snip of my JavaScript Fn:

<script type='text/javascript'>
    function checkQty(elem){
        var numericExpression = /^[0-9]+$/;
        if(elem.value.match(numericExpression)){
                return true;
            }else{
                alert("Quantity for RMA must be greater than zero and cannot be more than the original order!");
                elem.focus();
                return false;
        }
    }
    </script>

The function is called from the submit button, onClick:

<input type="submit" name="submit" onclick="checkQty(doc开发者_如何学JAVAument.getElementById('qty')";">  

I've tried:

var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression) || elem.value < 0 || elem.value > <? int($qty) ?>){

No dice....HELP!?!


Maybe try and view the source of the page and check if the $qty value is be printed out.

Also I think you need to change the or (||) to an and (&&) based on the original if statement, otherwise it will skip the limit checks.

Also echo the variable to print it out.

i.e.

var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression) && elem.value < 0 && elem.value > <? echo $qty ?>){


Have you tried?

  <input type="submit" name="submit" onclick="return checkQty(document.getElementById('qty'));"> 


You just need to make the PHP value available to the javascript e.g.

 <script type='text/javascript'>
 function checkQty(elem, max_value){
    if(parseInt(elem.value)>0
       && (parseInt(elem.value)<=max_value)){
            return true;
    }else{
            alert("Quantity for RMA must be greater than zero and less than original order!");
            elem.focus();
            return false;
    }
 }
 </script>
 ...
 <?php
     $max_value=(integer)method_of_fetching_max_value();
     print "<input type='submit' name='submit' 
             onclick='checkQty(document.getElementById(\"qty\", $max_value))'>  
     ";
 ?>

C.

0

精彩评论

暂无评论...
验证码 换一张
取 消