Validation based on a word list

Asked

Viewed 65 times

0

I want to validate a form with Jquery + Jquery Validation, using a list of authorized words.

Ex: var PalavrasAutorizadas = ['foo', 'bar', 'fizz', 'buzz' ];

if he enters any word that is not on the list he invalidates the form and does not send.

I managed to do just the opposite of what I wanted. You are only authorizing if you are not on the list, use this answer to assemble this script; https://stackoverflow.com/questions/37069086/validate-input-value-against-blacklist-array

Example in Fiddler https://jsfiddle.net/dorathoto/mfxn8mfj/2/

Javascript code:

var PalavrasAutorizadas = ['foo', 'bar', 'fizz', 'buzz' ];


jQuery.validator.addMethod("word", function(value) {
    return $.inArray(value, PalavrasAutorizadas) == -1;
}, 'a palavra não consta na lista');


$("#submit").validate({
    //errorPlacement: function(error, element) {},
    rules: {
        word: {
            required: true
        }
    },
    submitHandler: function(form) {
        alert('Submitted');
    }
});

UPDATE: I have tried to change the return of the array to 1 or true, but when testing each word does not work for all words, I think there is some detail in this function that I cannot notice.

  • It wouldn’t just change to $.inArray(value, Palavrasautorizadas) >= 0;

  • in theory it is, tried tbm as true, but change there and test every word, you will see that some work, others do not!

  • I think there’s some more detail missing, but I don’t know what it is.

  • In this fiddle inverti to 0, https://jsfiddle.net/mfxn8mfj/4/ can tell me a bug word so I can look for the problem.

2 answers

1


The inArray function will return the position of the array in which the searched element is, when it does not find, returns -1. Change the line return $.inArray(value, PalavrasAutorizadas) == -1; for return $.inArray(value, PalavrasAutorizadas) >= 0;

0

Dude, in Jquery’s doc he says:

Because Javascript Treats 0 as loosely Equal to false (i.e. 0 == false, but 0 !== false), to check for the presence of value Within array, you need to check if it’s not Equal to (or Greater than) -1.

I believe if you change the check to

return !($.inArray(value, PalavrasAutorizadas) >= -1);

I didn’t understand very well the logic of Validator, but to check the array, I believe it is this way hehe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.