svorobei svorobei - 1 year ago 64
Javascript Question

How to add input text validation for true and false?

Friends, i can't figure it out how to add text validation for

Point is user enters either
in the form. It's ok with checking numbers but i can't make up valid check for text input, e.g. true-e-e-e, fasleee, abra-cadabra, etc.

<script type="text/javascript">
function submitEmployeeForm() {

// getting the employee form values
var name = $('#name').val().trim();
var age = $('#age').val();
var admin = $('#admin').val();
if(name.length ==0) {
alert('Please enter name');
return false;

if(age <= 0) {
alert('Please enter valid age');
return false;

if(admin < 0 || admin > 1) {
alert('Please enter 0 for false, 1 for true');
return false;
return true;

I tried the following 2 options:

!admin.isEqual("false") || !admin.isEqual("true")

admin.valueOf()!="true" || admin.valueOf()!="false"

as a result is it does not pass any text including true and false.

Answer Source

If you want to accept only '0','1','true','false' as valid then use something like this

if (['0','1','false','true'].indexOf(admin.toLowerCase()) === -1) {
        alert('Please enter 0 for false, 1 for true');
        return false;

What we do is create an array which holds the valid texts, and then use indexOf(parameter) which searches the array for any element matching the passed parameter. If it is found it returns the position it was found in the array, if not it returns -1. So in your case if it is -1 which means that the passed value was not one of the accepted then do your thing.

Alternatively, you could use a checkbox instead of a text box, and just test if it is checked property is true.