Moha MBS
Moha MBS

Reputation: 15

Jquery validation show message of succes

I wanna to validate a string and show like a succes message if its good the validation, i have this:

$(document).ready(()=>{
    console.log("Pagina cargada...");
    jQuery.validator.addMethod('testWord', function (value, element) {
        var validator = this;
        console.log("Value ---> "+/^(El\s|La\s|L')\w+\sés\s\w+/.test(value))
        var res = /^(El\s|La\s|L')\w+\sés\s\w+/.test(value)
        if(res){
            console.log("in if")
            var errors = {};
            errors[element.name] =  "ok";
            validator.showErrors(errors);
            return false
        }else{
            console.log("in else")
            var errors = {};
            errors[element.name] =  "not ok";
            validator.showErrors(errors);
            return false
        }
    });
    $('form[id="second_form"]').validate({
        rules: {
          test: {
                required: true,
                testWord: true,
            }
        }
      });
    
})

And its not working, its not showing the message. This are the word i use to test:

I drop here a screenshot:

Upvotes: 1

Views: 72

Answers (1)

uingtea
uingtea

Reputation: 6554

it is because your form input doesn't have name="test" there also another problem, the method always return false.

$(document).ready(() => {
  console.log("Pagina cargada...");
  jQuery.validator.addMethod('testWord', function(value, element) {
    var validator = this;
    console.log("Value ---> " + /^(El\s|La\s|L')\w+\sés\s\w+/.test(value))
    var res = /^(El\s|La\s|L')\w+\sés\s\w+/.test(value)
    if (res) {
      console.log("in if")
      var errors = {};
      errors[element.name] = "ok";
      validator.showErrors(errors);
      return true; // <== originally return "false"
    } else {
      console.log("in else")
      var errors = {};
      errors[element.name] = "not ok";
      validator.showErrors(errors);
      return false
    }
  }, "bad input");
  $('#second_form').validate({
    rules: {
      test: {
        required: true,
        testWord: true,
      }
    }
  });

})
<form id="second_form">
  <input name="test" type="text">
</form>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.3/dist/jquery.validate.min.js"></script>

Upvotes: 1

Related Questions