Forum Discussion

LinahTul-Jam454's avatar
LinahTul-Jam454
Community Member
2 years ago

Validating keywords in Text Entry/Data entry fields

Hi!

I am working on a simulation where the user is required to add a comment that must include some keywords. Is there a way to validate the comment against those keywords and if all the keywords are there, the user may proceed to the next step otherwise it will show them the try again layer or take them to the "Simulation Failed" slide, depending on their number of attempts?

  • Hi Linah

    You can test whether a string contains a given substring in JavaScript by using the includes() method. So if you have a variable 'textString' and you want to know whether the text 'cat' was included then you might use something like:

    if textString.includes("cat") {

    ......}

    The attached example (which needs a LOT of work - but gives you the idea) contains the JavaScript:

    const key1 = "cat";
    const key2 = "dog";
    const key3 = "cow";
    var found = ["","",""];
    var player = GetPlayer();
    var textString = player.GetVar("TextEntry");
    if (textString.includes(key1)) {
        found[0] = ("you mentioned " + key1 + "\n");
        }
    if (textString.includes(key2)) {
        found[1] = ("you mentioned " + key2 + "\n");
        }
    if (textString.includes(key3)) {
        found[2] = ("you mentioned " + key3 + "\n");
        }
    player.SetVar("response",(found[0]+found[1]+found[2]));

    where TextEntry is the user input string you are testing and response is a text variable displayed in a text box on the screen