titanium 插件:validate ( titanium validate module)
访问量: 2625
refer to: https://github.com/haberdasheryjs/hdjs.validate.js ,它基于 validate.js
另外还有个插件:https://github.com/mwfire/titanium-module-validation,但是由于它大量的使用了 createXXField方法,属于view 与controller耦合的相当严重,所以不考虑。 (但是作者还是很有才的)
表单验证是永远需要的插件。这个的用法:
in your app/lib: hdjs.validate.js
in your view:
<Alloy>
<Window id="win">
<ScrollView>
<View id="container">
<TextField id="nameField" hintText='Enter name' />
<TextField id="emailField" hintText='Enter email address' />
<TextField id="passwordField" passwordMask="true" hintText='Enter password' />
<View id="privacyContainer">
<Label id="privacyLabel" text="Posts are private" />
<Switch id="privacySwitch" value="false" />
</View>
<Button id="submitButton" class="button" title="Submit" />
</View>
</ScrollView>
</Window>
</Alloy>
in your controller:
var validate = require('hdjs.validate');
var validator = new validate.FormValidator();
var validationCallback = function(errors) {
if(errors.length > 0) {
for (var i = 0; i < errors.length; i++) {
Ti.API.debug(errors[i].message);
}
alert(errors[0].message);
} else {
alert('Hooray! Your form is valid!');
}
};
var returnCallback = function() {
validator.run([
{
id: 'nameField',
value: $.nameField.value,
display: 'Name',
rules: 'required|min_length[6]|max_length[12]'
},
{
id: 'emailField',
value: $.emailField.value,
display: 'Email',
rules: 'required|valid_email'
},
{
id: 'passwordField',
value: $.passwordField.value,
display: 'Password',
rules: 'required|alpha_numeric|exact_length[10]'
},
{
id: 'privacyField',
value: $.privacySwitch.value,
display: 'Privacy',
rules: 'matches[true]'
}
], validationCallback);
};
$.submitButton.addEventListener('click', returnCallback);
$.win.open();
补充: 如果不使用插件的话,你的代码看起来就是这样的: (感谢:https://gist.github.com/dawsontoth/812022 )
function validateForm() {
var formIsValid = true;
function enforceTextFieldMinLength(field, minLength) {
if (!field.value || field.value.length < minLength) {
formIsValid = false;
}
}
function enforceLabelHasText(label) {
if (!label.text) {
formIsValid = false;
}
}
// check first name
enforceTextFieldMinLength(tfFirstName, 5);
// check last name
enforceTextFieldMinLength(tfLastName, 5);
// check label connected to gender drop down
enforceLabelHasText(lGender);
if (formIsValid) {
alert('Form is valid!');
}
else {
alert('Form is invalid...');
}
}