简体   繁体   中英

validate a field's value is greater than another field's value in php and javascript

I am working with form validations.

I have two text fields for adding budget. I want to check whether the value of total budget field is greater than that of daily budget in the click event of my submit button .I am using a form validation jquery plugin for validating my form. I want to customize that jquery with greaterthan rule.How can I validate a field's value is greater than another field's value in php and javascript.. I have tried with a method for greaterthan

Javascript:

method:
greaterThan: function(value, element, param)
    {
    var target = $(param);
    return value <= target.val();
    }

and

rules: {
            totalbudget: {
                   required: true,
                   greaterThan:"#daylybudget"
        },

But this is not working! How can I accomplish this?

var val1 = $('#textboxid1').val();
var val2 = $('#textboxid2').val();
var val3 = $('#textboxid3').val();

$('#submitbutton').click(function(){

if((val1 > val2) && (val2 > val3))
{

//prceed further
}
else 
{
alert('alert message');
}

});

NOTE: You need to include jquery before this code..

First, javascript is client side, php is server side. Depending on the type of validation you need you can implement one of these validations or even both of them.

Considering the following form

<form method="post">
    <input type="text" name="first_num" id="first_num" />
    <input type="text" name="second_num" id="second_num" />
    <input type="text" name="third_num" id="third_num" />
    <input type="submit" value="Send & validate" onclick="validate()" />
</form>

Here's a javascript way of doing it:

<script type="text/javascript">
    function validate()
    {
        var value1;
        var value2;
        var value3;
        value1 = parseFloat(document.getElementById('first_num').value);
        value2 = parseFloat(document.getElementById('second_num').value);
        value3 = parseFloat(document.getElementById('third_num').value);
        if (value1 > value2 && value2 > value3)
        {
            //we're ok
        }
        else
        {
            alert("Values are not as they should be");
            return false;
        }
    }
</script>

As for the php side:

<?php
    $value1 = $_POST['first_num'];
    $value2 = $_POST['second_num'];
    $value3 = $_POST['third_num'];

    if ($value1 > $value2 && $value2 > $value3)
    {
        //do whatever you want because the values are as you wish
    }
    else
    {
        //the values are not as they should be
    }
?>

Keep in mind that usually, for this kind of validation, javascript might be just enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM