oTree Forum >

Set the length of a String Field

#1 by Roger97

Hey! I'm new in otree, I'm trying to include in my app a Prolific page in which I ask the participants to write their prolific ID. Since it is a 24-character code, I want to have an error message if the length of the string is less than 24 characters. 

I tried to do like this but it does not work...

class Player(BasePlayer):
    prolific_ID = models.StringField(label="Please enter your Prolific ID:",
                                     max_length=24)

# FUNCTIONS
def validate(self):
      if len(self.prolific_ID) < 24:
            return 'your Prolific ID must be 24 characters long.'
            
 **********************************************************************************************************
 This is the html
    {{ block content }}
    {{ formfields }}

    <p align="right">
<button class="otree-btn-next btn btn-primary">NEXT</button>
</p>
   {{ endblock }}         
*************************************************************************************************************
thank you in advance!

#2 by Fanist

see this code for a reference


{{ block title }}<center><p>Welcome</p></center>{{ endblock }}
{{ block content }}

    <center>
        {{ formfields }}
    </center>



<center>
    <button type="button" class="btn btn-primary" onclick="checkSubmit()">Next</button>
</center>

<!--The code below prevents participants from submitting their Prolific ID va the Enter button.-->
<script type="text/javascript">
window.addEventListener('keydown',function(e){if(e.keyIdentifier=='U+000A'||e.keyIdentifier=='Enter'||e.keyCode==13){if(e.target.nodeName=='INPUT'&&e.target.type=='text'){e.preventDefault();return false;}}},true);
</script>

<script>
    function checkSubmit() {
        let form = document.getElementById('form');
        let isValid = form.reportValidity();
        if (!isValid) return;

        let warnings = [];

        let prolific_id = forminputs.prolific_id.value;

        // Warn of Prolific ID is too short
        if (prolific_id.length < 10) {
            warnings.push("Are you sure about your id?")
        }
        
        // Press OK to proceed anyway
        if (warnings.length > 0) {
            warnings.push("Press OK to proceed anyway.")
            let confirmed = window.confirm(warnings.join('\r\n'));
            if (!confirmed) return;
        }
        form.submit();
    }
</script>

{{ endblock }}

Write a reply

Set forum username