emberjs input checkValidity and setCustomValidity

322 Views Asked by At

Is there a way to use checkValidity() setCustomValidity() within ember? For example, in my controller upon submission I have:

var inpObj = this.get('name');
if (inpObj.checkValidity() == false) {
    alert('ok');
}

and of course this is my handlebar code:

{{input id="name" type="text" value=name placeholder="Your Name" required="true"}}

Upon submission of this, I get this error message:

inpObj.checkValidity is not a function

2

There are 2 best solutions below

2
Daniel On

You would need to get HTML5 element instead of string to call checkValidity function.

var inpObj = this.get('name'); // this is only a string

You can use jQuery instead:

var inpObj = Ember.$('#name')[0];

if (inpObj.checkValidity() == false) {
  alert('ok');
}

Working demo.

0
sbatson5 On

If you want to avoid jQuery, you could set an action on your submit button that runs the valid check for you.

<button {{action "submitForm"}}>Your Button</button>

Then have an action in your contoller:

actions: {
  submitForm() {
    var inpObj = this.get('name');
    if(!inpObj.checkValidity()) {
      // error handling
      alert('ok');
    } else {
      // save your data, or whatever you need to do
      this.transitionTo('some.route');
    }
  }
}