Small fix needed... please help

Discussion in 'JavaScript' started by oo7ml, Oct 19, 2007.

  1. #1
    Hi have some form validation on a small page i have. It checks that the fields A, B, C & D are are not empty. However i want to have validation on the D field to make sure that only the values 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 are allowed only and not 11, 12... or not 01, 02... - only the scores 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

    Here is the code i have now:

    
    <input type="image" src="../images/accept.jpg" onMouseOut=this.src='../images/accept.jpg' onMouseOver=this.src='../images/accept_o.jpg' onClick="if(document.getElementById('A').value == '' || document.getElementById('B').value == '' || document.getElementById('C').value == '' || document.getElementById('D').value == '') { alert('Ooops... Please fill in A, B, C, D'); return false;}" />
    HTML:
    Can someone please add on the code needed for this please as i need to fix it urgently, thanks for your help
     
    oo7ml, Oct 19, 2007 IP
  2. upl8t

    upl8t Peon

    Messages:
    80
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Add the following function somewhere in your javascript:

    function isInteger(s) {
    return (s.toString().search(/^-?[0-9]+$/) == 0);
    }

    Then in the onClick validation:

    onClick="if(document.getElementById('A').value == '' ||.... add:

    || !isInteger(document.getElementById('A').value) || parseInt(document.getElementById('A').value) < 1 || parseInt(document.getElementById('A').value) > 10

    For each of the A, B, C, etc..

    Of course to make it a bit cleaner you can combine all the checks into a single function "badVariable(value)...."
    function badVariable(value)
    return value == "" || !isInteger(value) || parseInt(value) < 1 || parseInt(value) > 10
    }

    and then just run that function on each of the A, B, etc..

    onClick="if(badVariable(document.getElementById('A').value) || badVariable(document.getElementById('A').value) ..... etc.
     
    upl8t, Oct 22, 2007 IP