数据验证:在columns中设置validator,进行同步或异步验证,还可添加beforeValidate, afterValidate函数,allowInvalid:true可以不用验证
var people = [ {id: 1, name: {first: ‘Joe‘, last: ‘Fabiano‘}, ip: ‘0.0.0.1‘, email: ‘[email protected]‘}, {id: 2, name: {first: ‘Fred‘, last: ‘Wecler‘}, ip: ‘0.0.0.1‘, email: ‘[email protected]‘}, {id: 3, name: {first: ‘Steve‘, last: ‘Wilson‘}, ip: ‘0.0.0.1‘, email: ‘[email protected]‘}, {id: 4, name: {first: ‘Maria‘, last: ‘Fernandez‘}, ip: ‘0.0.0.1‘, email: ‘[email protected]‘}, {id: 5, name: {first: ‘Pierre‘, last: ‘Barbault‘}, ip: ‘0.0.0.1‘, email: ‘[email protected]‘}, {id: 6, name: {first: ‘Nancy‘, last: ‘Moore‘}, ip: ‘0.0.0.1‘, email: ‘[email protected]‘}, {id: 7, name: {first: ‘Barbara‘, last: ‘MacDonald‘}, ip: ‘0.0.0.1‘, email: ‘[email protected]‘}, {id: 8, name: {first: ‘Wilma‘, last: ‘Williams‘}, ip: ‘0.0.0.1‘, email: ‘[email protected]‘}, {id: 9, name: {first: ‘Sasha‘, last: ‘Silver‘}, ip: ‘0.0.0.1‘, email: ‘[email protected]‘}, {id: 10, name: {first: ‘Don‘, last: ‘Pérignon‘}, ip: ‘0.0.0.1‘, email: ‘Don.Pé[email protected]‘}, {id: 11, name: {first: ‘Aaron‘, last: ‘Kinley‘}, ip: ‘0.0.0.1‘, email: ‘[email protected]‘} ], example1 = document.getElementById(‘example1‘), example1console = document.getElementById(‘example1console‘), settings1, ipValidatorRegexp, emailValidator; ipValidatorRegexp = /^(?:\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b|null)$/; emailValidator = function (value, callback) { setTimeout(function(){ //还能这样验证 if (/[email protected]+/.test(value)) { callback(true); } else { callback(false); } }, 1000); }; settings1 = { data: people, //hooks beforeChange: function (changes, source) { //changes是数组,数组的元素也是数组,包含四个属性0:10,1:‘name.last‘,2:‘Kinley‘,3:‘foo‘ for (var i = changes.length - 1; i >= 0; i--) { // gently don‘t accept the word "foo" (remove the change at index i) //如果想改为foo,会把这次修改删掉 if (changes[i][3] === ‘foo‘) { changes.splice(i, 1); } // if any of pasted cells contains the word "nuke", reject the whole paste //如果想改为nuke,只是拒绝,而不会删除此次修改 else if (changes[i][3] === ‘nuke‘) { return false; } // capitalise first letter in column 1 and 2 else if ((changes[i][1] === ‘name.first‘ || changes[i][1] === ‘name.last‘) && changes[i][3].charAt(0)) { changes[i][3] = changes[i][3].charAt(0).toUpperCase() + changes[i][3].slice(1); } } }, afterChange: function (changes, source) { if (source !== ‘loadData‘) { example1console.innerText = JSON.stringify(changes); } }, colHeaders: [‘ID‘, ‘First name‘, ‘Last name‘, ‘IP‘, ‘E-mail‘], columns: [ {data: ‘id‘, type: ‘numeric‘}, {data: ‘name.first‘}, {data: ‘name.last‘}, //给ip加事件处理程序,可以不通过验证 {data: ‘ip‘, validator: ipValidatorRegexp, allowInvalid: true}, {data: ‘email‘, validator: emailValidator, allowInvalid: false} ] }; var hot = new Handsontable(example1, settings1);
时间: 2024-10-25 01:48:11