我创建了一个名为form-field-input的通用表单组件,它可以在焦点输出时验证用户输入.
表单字段-input.hbs
<label>{{label}}</label>
{{input
placeholder=label
value=value
focus-out='validate'
required=required
type=type
}}
<p>{{errorMessage}}</p>Run Code Online (Sandbox Code Playgroud)
表单字段-input.js
actions: {
validate: function() {
var type = this.get('type');
this.set('checked', true);
if (this.get('required')) {
if (this.get('value') === '') {
this.set('invalid', true);
this.set('valid', false);
this.set('errorMessage', 'This field cannot be blank');
return
}
}
if (type === 'Email') {
this.send('validateEmail');
}
...
},
}Run Code Online (Sandbox Code Playgroud)
如果我将组件的多个实例放入一个表单中(如下所示),当用户从每个输入中聚焦时,验证将完美地工作.
<form {{action "login" on="submit"}}>
{{form-field-input label='Email' value=email type='Email' required=true }}
{{form-field-input label='Password' value=password type='Password' required=true}}
{{input type="submit" value="Log In"}}
</form>Run Code Online (Sandbox Code Playgroud)
我想在用户单击提交时验证每个表单字段输入组件(因此单击提交而不填写任何字段将触发每个所需表单字段组件上的验证错误消息). …