@@ -29,6 +29,7 @@ const common_input_tpl = `
2929
3030export class Input extends InputItem {
3131 static accept_input_types : string [ ] = [ "text" , "password" , "number" , "float" , "color" , "date" , "range" , "time" , "email" , "url" ] ;
32+ previous_value = '' ;
3233
3334 constructor ( spec : any , task_id : string , on_input_event : ( event_name : string , input_item : InputItem ) => void ) {
3435 super ( spec , task_id , on_input_event ) ;
@@ -61,11 +62,13 @@ export class Input extends InputItem {
6162 this . on_input_event ( "blur" , this ) ;
6263 } ) ;
6364 }
64- if ( spec . onchange ) {
65- input_elem . on ( "input" , ( e ) => {
65+
66+ input_elem . on ( "input" , ( e ) => {
67+ this . rectify_input ( )
68+ if ( spec . onchange ) {
6669 this . on_input_event ( "change" , this ) ;
67- } ) ;
68- }
70+ }
71+ } ) ;
6972
7073 // 将额外的html参数加到input标签上
7174 const ignore_keys = make_set ( [ 'action' , 'type' , 'label' , 'invalid_feedback' , 'valid_feedback' , 'help_text' ,
@@ -78,6 +81,36 @@ export class Input extends InputItem {
7881 return this . element ;
7982 }
8083
84+ rectify_input ( ) {
85+ let val = '' + this . element . find ( 'input' ) . val ( ) as string ;
86+ let re ;
87+ if ( this . spec [ 'type' ] == 'number' ) {
88+ re = / ^ [ + - ] ? \d * $ / ;
89+ } else if ( this . spec [ 'type' ] == 'float' ) {
90+ re = / ^ [ + - ] ? \d * \. ? \d * $ / ;
91+ }
92+ if ( re && ! re . test ( val ) ) {
93+ this . element . find ( 'input' ) . val ( this . previous_value ) ;
94+ } else {
95+ this . previous_value = val ;
96+ }
97+ }
98+
99+ // 检查输入项的有效性,在表单提交时调用
100+ check_valid ( ) : boolean {
101+ let valid = ! Number . isNaN ( this . get_value ( ) ) || this . element . find ( 'input' ) . val ( ) === '' ;
102+ if ( ! valid ) {
103+ this . update_input_helper ( - 1 , {
104+ 'valid_status' : false
105+ } ) ;
106+ } else {
107+ this . update_input_helper ( - 1 , {
108+ 'valid_status' : 0 , // remove the valid status
109+ } ) ;
110+ }
111+ return valid ;
112+ }
113+
81114 update_input ( spec : any ) : any {
82115 let attributes = spec . attributes ;
83116 if ( 'datalist' in attributes ) {
@@ -90,6 +123,7 @@ export class Input extends InputItem {
90123 }
91124
92125 get_value ( ) : any {
126+ this . rectify_input ( )
93127 let val = this . element . find ( 'input' ) . val ( ) ;
94128 if ( this . spec [ 'type' ] == 'number' )
95129 val = parseInt ( val as string ) ;
0 commit comments