Skip to content Skip to sidebar Skip to footer

Check If String Exists In Text Field

I have a basic form which contains a text field like this: But I want to control if exist any predefined word like 'Mickey', If it does not exist, I want to block submitting, like

Solution 1:

You could use HTML5 form validation. Simply make the field required and give it a pattern. No JS required (although you might choose a polyfill for old browsers).

Try and submit this form without matching the pattern:

<form>
    <input name="myInput" 
           required="required" 
           placeholder="Must contain Mickey" 
           pattern=".*Mickey.*" 
           title="It must contain Mickey somewhere."
    />
    <input type="submit" />
</form>

Also: Untested example with basic JS fallback


Solution 2:

HTML

<input type="submit" id="button" class="button" onclick="return submitcheck();" />

Script

function submitcheck() {
    if(document.getElementById("textField").value.indexOf("Mickey") > -1) {
         return true;
    } else {
         return false;
    }
}

If n is not -1 then Mickey was in the string.


Solution 3:

Assuming you have a 'text field' DOM element somewhere:

if($(<textfield>).val().indexOf($(<inputID>).val()) > -1){
    //things to be done if 'Mickey' present
}

You can do this validation on click of the submit button.


Post a Comment for "Check If String Exists In Text Field"