简体   繁体   中英

Validation for html5 input type number

I would like to show 2 different validation messages for the following input type

<input type="number" step="1" formControlName="Ordinal" />

I'm using reactive forms with a formGroup that is similar to this

formBuilder.group({
  ..
  Ordinal: [0, [Validators.required, CustomValidators.integer]],
  ..
});

One Validator Validators.required should show a required message if there is no input at all. The other Validator Validator.integer should show a message if an invalid number is entered.

The current implementation of Validation.integer looks like this

export function integer(control: FormControl) {
  const value = control.value;
  if ((parseFloat(value) === parseInt(value, 10)) && !isNaN(value) || value === '' || value === null) {
    return null;
  } else {
    return {
      notNumeric: true
    };
  }
}

My problem is that with type="number" the browser returns null in both cases (when input is empty / when number is invalid). How can i distinguish these two states?

    to check numeric value I thinks `isNaN and  Number.isInteger()` would be enough 

    Please check the following updated conditions :-


    export function integer(control: FormControl) {
      const value = control.value;
      if(value === 'null' || value === undefined || value === '' ){
       return isRequired: true
      }
     else if ((!Number.isInteger(value) || !isNaN(value))) {
        return null;
      } else {`enter code here`
        return {
          notNumeric: true
        };
      }
    }


    hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM