Validation based on a list of words

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 in the list he invalidates the form and does not send it.

I was able to do exactly the opposite of what I wanted. You are only authorizing if it is not in the list, use this response to mount this script; link

Example in fiddler link

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 can not understand.     

asked by anonymous 06.09.2017 / 21:16

2 answers

1

The inArray function returns 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; by return $.inArray(value, PalavrasAutorizadas) >= 0;

    
06.09.2017 / 21:30
0

Man, in the Jquery doc he says:

  

Because JavaScript treats 0 as loosely equal to false (ie 0 == false, but 0! == false), to check for the presence of value within array, you need to check if it is not equal to ) -1.

I believe that if you change the check to

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

I do not really understand the logic of the validator, but to do the array check, I think it's that way hehe

    
06.09.2017 / 21:44